Created
August 30, 2024 06:33
-
-
Save vprabhu/ebce4cf922f50325f3f82b400681c0ac to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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