Skip to content

Instantly share code, notes, and snippets.

View tdcolvin's full-sized avatar

Tom Colvin tdcolvin

  • Basingstoke, UK
  • 18:42 (UTC +01:00)
View GitHub Profile
viewModelScope.launch {
// Time passing before we start collecting...
delay(4000)
// Start collecting the flow
sharedFlow.collect {
println(it)
}
}
val sharedFlow = MutableSharedFlow<Int>()
viewModelScope.launch {
var count = 0
// Every 500ms, emit a new number in sequence
while (true) {
delay(500)
sharedFlow.emit(count++)
}
@Composable
fun FlashingCountingButton() {
val scope = rememberCoroutineScope()
var buttonColor by remember { mutableStateOf(Color.Red) }
var count by remember { mutableStateOf(1) }
Column {
Button(colors = ButtonDefaults.buttonColors(backgroundColor = buttonColor),
onClick = {
val job = scope.launch {
val job = scope.launch {
while(true) {
delay(500)
buttonColor = Color(Random.nextInt(0xFF), Random.nextInt(0xFF), Random.nextInt(0xFF), 0xFF)
}
}
scope.launch {
delay(2000)
job.cancel()
@Composable
fun RandomColourButton() {
val scope = rememberCoroutineScope()
var buttonColor by remember { mutableStateOf(Color.Red) }
Column {
Button(colors = ButtonDefaults.buttonColors(backgroundColor = buttonColor),
onClick = {
scope.launch {
while(true) {
@tdcolvin
tdcolvin / main.kt
Last active January 19, 2024 17:52
suspend fun countToAHundredBillion() {
var count = 0L
while(count < 100_000_000_000) {
count++
// Every 10,000 we yield to the coroutine
// dispatcher, allowing this loop to be
// cancelled if needed.
if (count % 10_000 == 0) {
@tdcolvin
tdcolvin / main.kt
Last active January 19, 2024 17:52
// !!!!! DON'T DO THIS !!!!!
suspend fun countToAHundredBillion_unsafe() {
var count = 0L
// This suspend fun won't be cancelled if the coroutine
// that's running it gets cancelled, because it doesn't
// ever yield.
while(count < 100_000_000_000) {
count++
}
suspend fun deleteAllNotes() = withContext(...) {
// Create a scope. The suspend function will return when *all* the
// scope's child coroutines finish.
coroutineScope {
launch { remoteDataSource.deleteAllNotes() }
launch { localDataSource.deleteAllNotes() }
}
}
fun flashTheLights() {
viewModelScope.launch {
// This seems like an unsafe infinite loop, but in fact
// it'll shut down when the viewModelScope is cancelled.
while(true) {
delay(1_000)
lightState = !lightState
}
}
}
suspend fun saveNote(note: Note) {
withContext(Dispatchers.IO) {
notesRemoteDataSource.saveNote(note)
}
}