What is the correct way to unsubscribe from a Flow...
# flow
c
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
Copy code
flow.transformWhile { it ->
    emit(it)
    return it !is Success
}.collect { ... }
c
Thanks!
d
if you don't need the
Success
value in
collect
you can also use
takeWhile { it !is Success }
e
I assume you mean
return@transformWhile
there
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
if you don't need the value at all, there's other terminal operators like
Copy code
flow.any { it is Success }
c
Thanks a lot, I didn't realize
first
any
etc where available on flow