https://kotlinlang.org logo
Title
n

natario1

02/12/2021, 4:49 PM
Is there any operator for
Flow<Flow<T>>
like
flatten*
which can cancel child flow collection when a new parent value is emitted? Say you have
fun parentFlow(): Flow<String> = ...
fun childFlow(id: String): Flow<Result> = ... // id comes from parentFlow
My goal is to have a single
Flow<Result>
, taking the id from parent flow. One way to do this is:
val merged: Flow<Flow<Result>> = parentFlow().map { childFlow(it) }
val flat: Flow<Result> = merged.flattenConcat()
However in my case the parent id represents a kind of state, so when a new id is emitted, the flow should stop collecting the previous
childFlow
. I'm struggling to find an elegant way to do this. I could collect the child inside the parent body (inside
flow { }
for example), but then not sure how to cancel the previous one
w

wasyl

02/12/2021, 4:52 PM
Do you mean
Flow<T>.flatMapLatest
?
n

natario1

02/12/2021, 5:05 PM
That's perfect! Thank you!
👍 1
o

Orhan Tozan

02/14/2021, 9:17 PM
Why isnt there a .flattenLatest() like flattenMerge()?