https://kotlinlang.org logo
#flow
Title
# flow
a

Alexander Black

01/19/2022, 2:53 AM
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

Alexander Black

01/19/2022, 3:10 AM
So exactly this, but if the predicate was another flow not a boolean.
a

Alexander Black

01/19/2022, 3:30 AM
@gildor perfect! Thank you so much
👌 1
b

baxter

01/19/2022, 4:47 AM
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

Nick Allen

01/19/2022, 7:04 AM
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

Alexander Black

01/19/2022, 5:36 PM
@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.
2 Views