To stop or unsubscribe from a Kotlin Flow, you can call the cancel()
function on the corresponding Job
object that was returned when you started collecting the flow:
val job = launch {
someFlow.collect {
// do something with the emitted value
}
}
// to unsubscribe:
job.cancel()
Alternatively, you can use the onCompletion
, onError
or catch
operators to handle the completion or error of the flow and perform any necessary cleanup:
someFlow
.onCompletion {
// cleanup code
}
.onError {
// handle error and cleanup code
}
.catch {
// handle exception and cleanup code
}
.collect {
// do something with the emitted value
}
Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss
Asked: 2022-05-05 11:00:00 +0000
Seen: 8 times
Last updated: Oct 03 '21
Why can't IntelliJ IDEA detect the Kotlin multiplatform library?
How to implement map function on Kotlin's Stateflow?
What is the correlation between coroutines and the Kotlin Gradle Plugin?
When the library throws a JsonDataException, why does the Kotlin Moshi adapter return null?
What are the typical approaches found in a Gradle build script?
Which languages are appropriate to use for a contemporary website?