https://kotlinlang.org logo
#flow
Title
# flow
m

muthuraj

09/07/2020, 9:00 AM
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

wasyl

09/07/2020, 9:10 AM
Would
Copy code
scope.launch {
  state.collectLatest(::handleState)
}
be what you’re looking for?
m

muthuraj

09/07/2020, 10:06 AM
Wow, this is it. Thank you so much.
👍 1
3 Views