I want to cancel kotlin flow if certain condition occurred in code.
Suppose i have a method as following
fun test(): Flow<String> = flow {
val lst = listOf("A", "B", "C")
while(true) {
lst.forEach { emit(it) }
//If some condition occurs, need to return from here, else continue
//How to stop flow here
}
}
and calling it like
test().collect { println(it)}
question is, how to stop flow to produce anything on certain conditions (from flow builder or outside of it)?
fun test(): Flow<String> = flow {
val lst = listOf("A", "B", "C")
while(true) {
lst.forEach { emit(it) }
if (someCondition) {
return@flow
}
}
}
return@flow
instantly returns from flow
lambda, so the flow will be ended. As another option, you can just break
your while(true)
loop when your condition occurs.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With