Skip to content

Instantly share code, notes, and snippets.

@vprabhu
Created August 30, 2024 06:33
Show Gist options
  • Save vprabhu/ebce4cf922f50325f3f82b400681c0ac to your computer and use it in GitHub Desktop.
Save vprabhu/ebce4cf922f50325f3f82b400681c0ac to your computer and use it in GitHub Desktop.
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.onCompletion
suspend fun main(): Unit = coroutineScope {
// cancel the job
val job = launch {
sampleFlow()
.onCompletion { cause ->
if (cause is CancellationException) {
println("Flow cancelled Manually by job ")
}
}
.collect {
println("Type 1 Received $it")
}
}
delay(550)
job.cancel()
/**
* Output :
* Type 1 Received 1
* Type 1 Received 3
* Flow cancelled Manually by job
*/
// cancel the code in scope
launch {
sampleFlow()
.onCompletion { cause ->
if (cause is CancellationException) {
println("Flow cancelled Manually in scope")
}
}.collect {
println("Type 2 Received $it")
if (it == 3) {
cancel()
}
}
}.join()
/**
* Output :
* Type 2 Received 1
* Type 2 Received 3
* Flow cancelled Manually in scope
*/
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment