Skip to content

Instantly share code, notes, and snippets.

@octylFractal
Last active July 5, 2020 18:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save octylFractal/9cd8b2cd0c71c123d657acde8fef3d31 to your computer and use it in GitHub Desktop.
Save octylFractal/9cd8b2cd0c71c123d657acde8fef3d31 to your computer and use it in GitHub Desktop.
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