can someone lead me to a way to collect a flow unt...
# flow
a
can someone lead me to a way to collect a flow until some other flow emits something as a condition?? example:
Copy code
someFlow.onEach { /*Do something*/}.takeUntil(someOtherFlowAsPredicate).collect()
a
So exactly this, but if the predicate was another flow not a boolean.
a
@gildor perfect! Thank you so much
👌 1
b
I mean... the down and dirty way of achieving what you are looking to do would be:
Copy code
fun <T> Flow<T>.takeUntil(otherFlow: Flow<*>): Flow<T> {
    return channelFlow {
        val job = launch {
            collect { send(it) }
        }

        otherFlow.first()
        job.cancel()
    }
}
But I literally just wrote this in about 5 min. The idea here is that both flows start to collect, but only the upstream emits. The moment that
otherFlow
emits a single item, the job collecting the upstream is cancelled, and this flow ends.
🎉 2
You'd be able to customize this too by adding in some sort of terminal item to send downstream at the end of the
channelFlow
.
🎉 2
n
Generally, when I want to cancel behavior based on a
Flow
, I look to the
*Latest
methods. For example:
Copy code
flow{
   emit(someFlow)
   otherFlow.first()
   emit(emptyFlow())
}.flatMapLatest {it}
Not any better than what’s above (and untested, on phone) but just some advice for getting to a solution when you end up in a similar situation.
🎉 2
a
@baxter @Nick Allen Thank you both very much for the code/advice. I very much appreciate it.
I've never tried the flatMapLatest function... that's really cool! going to give that a shot.