Im trying to switch between flows depending on ano...
# flow
m
Im trying to switch between flows depending on another flow 🙂
Copy code
val result = state.transformLatest {
            when (it) {
                "a" -> emitAll(emitter("A"))
                "c" -> emitAll(emitter("C"))
            }
        }

        result.collect {
            println(it)
        }
this will print a flow of A+<counter> or “C” +<counter> depending on the last value from “state”. I would like to ignore “unknown” states, but since transformLatest cancels the previous flow even if i don’t emit anything new, setting the state to “B” will just cancel the output, not continue on the previous selected output. Is there a nice way to achieve what I want?
w
you could filter the unknown states before
transformLatest
?
m
Yes, its possible, but then I’ll have 2 places to update and keep in sync when new values should be “known”
đź‘Ś 1
Copy code
state.filter{it=="a" || it=="c"}.transformLatest
it feels a bit redundant 🙂 I would like to have a transformLatest that only cancels the old job if I emit a new flow, not on all new incoming values.
w
I don’t think there’s an API for that, other than being able to implement your own operator (which in case of
transform
isn’t that straightforward I think). I’d probably just go for some pattern like
Map<String, ???>
so that I have single source of truth for
filter { handlers.contains(it) }
and for the transform
m
great minds and all that 🙂 I ended up fixing it with a
mapOf<State, Flow<String>>
and filter
d
How about:
Copy code
myFlow
   .filter { it.isNotUnknown() }
   .distinctUntilChanged()
   .flatMapLatest {
      // Choose output flow
   }
b
you can just map letter to flow before transform latest:
Copy code
state.mapNotNull { 
    when (it) {
       "a" -> emitter("a")
       "b" -> emitter("b")
       else -> null
     }
}.flatMapLatest { it }
đź‘Ś 1
đź‘Ź 1
đź‘Ť 1