https://kotlinlang.org logo
Title
c

CLOVIS

08/22/2021, 2:48 PM
What is the correct way to unsubscribe from a Flow?
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
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
if you want the value itself you can do things like
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
flow.any { it is Success }
c

CLOVIS

08/23/2021, 7:43 AM
Thanks a lot, I didn't realize
first
any
etc where available on flow