I'm using `StateFlow` to emit some states and do s...
# flow
m
I'm using
StateFlow
to emit some states and do some work based on that. My code looks like this
Copy code
state.onEach(this::handleState)
     .launchIn(scope)
Now since the
onEach
block is a suspending function, if another state is emitted while it is executing, it doesn't cancel the current suspending function. Instead it waits for the
handleState
function to finish it's execution and then next state's handling is being done. I realise this is actually done intentionally to handle back pressure and all, but what I want is to cancel
onEach
execution when new state is received and run
onEach
for the new state. Currently I'm running the
handleState
block in another coroutine using
scope.launch { }
, store that job as member variable, then cancel that in
onEach
before launching new coroutine. Is there any other way to achieve this?
w
Would
Copy code
scope.launch {
  state.collectLatest(::handleState)
}
be what you’re looking for?
m
Wow, this is it. Thank you so much.
đź‘Ť 1