Skip to content

Instantly share code, notes, and snippets.

@vprabhu
Created August 30, 2024 06:36
Show Gist options
  • Save vprabhu/1a9defc5e8decffc619b5ed746b43d17 to your computer and use it in GitHub Desktop.
Save vprabhu/1a9defc5e8decffc619b5ed746b43d17 to your computer and use it in GitHub Desktop.
import kotlinx.coroutines.cancel
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.flow.cancellable
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.flow.onCompletion
import kotlinx.coroutines.launch
import kotlin.coroutines.cancellation.CancellationException
suspend fun main(): Unit = coroutineScope {
launch {
flowOf(1,3,5)
.onCompletion { cause ->
if (cause is CancellationException) {
println("Flow cancelled $cause")
}
}
.cancellable()
.collect {
println("Received $it")
if (it == 3) {
cancel()
}
}
}.join()
/**
* only using collect()
* output :
* Received 1
* Received 3
* Received 5
*
* using ensureActive() in onEach{}
* Output:
* Received 1
* Received 3
* Flow cancelled kotlinx.coroutines.JobCancellationException:
* StandaloneCoroutine was cancelled; job=StandaloneCoroutine{Cancelling}@689a4a73
*
* using cancellable() instead of onEach{}
*Output :
* Received 1
* Received 3
* Flow cancelled kotlinx.coroutines.JobCancellationException:
* StandaloneCoroutine was cancelled; job=StandaloneCoroutine{Cancelling}@45939480
*
*/
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment