What is the correct way to unsubscribe from a Flow?
Copy code
val flow = myFlow()
flow.collect {
if (it is Success) {
// I found the value I was waiting for,
// stop collecting values and go back to executing the function
}
}
d
diesieben07
08/22/2021, 2:57 PM
Copy code
flow.transformWhile { it ->
emit(it)
return it !is Success
}.collect { ... }
c
CLOVIS
08/22/2021, 3:02 PM
Thanks!
d
diesieben07
08/22/2021, 3:04 PM
if you don't need the
Success
value in
collect
you can also use
takeWhile { it !is Success }
e
ephemient
08/23/2021, 4:02 AM
I assume you mean
return@transformWhile
there
ephemient
08/23/2021, 4:04 AM
if you want the value itself you can do things like
Copy code
flow.firstOrNull { it is Success } // doesn't cast to Success?
flow.filterIsInstance<Success>().firstOrNull() // does
ephemient
08/23/2021, 4:05 AM
if you don't need the value at all, there's other terminal operators like