How do I make `Flow.transformLatest()` complete wh...
# getting-started
d
How do I make
Flow.transformLatest()
complete when upstream completes?
Copy code
upstream
  .transformLatest { state ->
    emitAll(dataForState(state))
  }
say upstream is
Copy code
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
I believe there is a
transformWhile
.
d
Sure, what if the
Copy code
observeState
  .takeWhile { state -> isStopState(state) }
comes from upstream / a function I've no control in?
d
Oh nvm, I think just understood the problem.
d
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
d
You can use
onCompletion
and emit a cancellation token.
d
@Dominaezzz Actually, even with
transformWhile
is not possible what I would need is a
transformLatestWhile
(see my modified question)
d
Yeah I realized.
Cancellation token could just be null I guess.
d
I did something like this
Copy code
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
Nice