https://kotlinlang.org logo
Title
d

Daniele Segato

12/23/2020, 12:16 PM
How do I make
Flow.transformLatest()
complete when upstream completes?
upstream
  .transformLatest { state ->
    emitAll(dataForState(state))
  }
say upstream is
currentState
  .takeWhile { state -> isCloseNowState(state) }
This would be easy if I had control of it, I could use
transformWhile
, what if I don't? How do I cancel
dataForState
when upstream completes? Actually, this is challenging even when I use
transformWhile()
cause it is not cancelling the previous one I'd need a
transformLatestWhile
d

Dominaezzz

12/23/2020, 12:17 PM
I believe there is a
transformWhile
.
d

Daniele Segato

12/23/2020, 12:18 PM
Sure, what if the
observeState
  .takeWhile { state -> isStopState(state) }
comes from upstream / a function I've no control in?
d

Dominaezzz

12/23/2020, 12:18 PM
Oh nvm, I think just understood the problem.
d

Daniele Segato

12/23/2020, 12:19 PM
In other words, how do I tell
transformLatest
to stop when upstream completes?
You are right,
transformWhile
works perfectly if you control all the chain. I should have asked the question better
@Dominaezzz Actually, even with
transformWhile
is not possible what I would need is a
transformLatestWhile
(see my modified question)
d

Dominaezzz

12/23/2020, 12:25 PM
You can use
onCompletion
and emit a cancellation token.
Yeah I realized.
Cancellation token could just be null I guess.
d

Daniele Segato

12/23/2020, 12:37 PM
I did something like this
upstream
  .map { it as MyState? }
  .onComplete { emit(null) }
  .transformLatest { state ->
    if (state != null) {
      emitAll(dataForState(state)
    }
  }
if I had a nullable emission I could have build a wrapper and did the same
d

Dominaezzz

12/24/2020, 1:35 PM
Nice