Alexander Black
01/19/2022, 2:53 AMsomeFlow.onEach { /*Do something*/}.takeUntil(someOtherFlowAsPredicate).collect()
baxter
01/19/2022, 3:04 AMAlexander Black
01/19/2022, 3:10 AMgildor
01/19/2022, 3:23 AMAlexander Black
01/19/2022, 3:30 AMbaxter
01/19/2022, 4:47 AMfun <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.channelFlow
.Nick Allen
01/19/2022, 7:04 AMFlow
, I look to the *Latest
methods. For example:
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.Alexander Black
01/19/2022, 5:36 PM