-
-
Save octylFractal/9cd8b2cd0c71c123d657acde8fef3d31 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.* | |
suspend fun main() { | |
coroutineScope { | |
val sequence = generateSequence(0) { it + 1 } | |
.asFlow() | |
.take(5) | |
.onEach { | |
// purposefully non-cancellable sleep | |
withContext(NonCancellable) { | |
delay(1000) | |
} | |
} | |
val nonCancelJob = launch { | |
sequence | |
.collect { | |
System.err.println("Non-cancellable: $it") | |
} | |
} | |
val cancelJob = launch { | |
sequence | |
.cancellable() | |
.collect { | |
System.err.println("Cancellable: $it") | |
} | |
} | |
delay(2000) | |
nonCancelJob.cancel() | |
cancelJob.cancel() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment