https://kotlinlang.org logo
Title
b

benkuly

01/17/2022, 1:31 PM
flow.flatMapLatest { flowValue -> 
    stateFlowDependingOnFlowValue(flow1Value,scope) // internally does something like `.stateIn(scope)`
}
Given this code, every time
flatMapLatest
is called, a new coroutine is spawned in the scope. Is there a way to use a scope, which is only active within
flatMapLatest
, so old calculations would be cancelled?
b

bezrukov

01/17/2022, 1:36 PM
smth like transformLatest + coroutineScope should work:
flow.transformLatest { flowValue ->
   coroutineScope {
      emitAll(stateFlowDependingOnFLowValue(flowValue, this))
   }
}
b

benkuly

01/17/2022, 1:39 PM
Wouldn't
coroutineScope
prevent
transformLatest
to complete, because of
stateIn
?
b

bezrukov

01/17/2022, 1:46 PM
of course it will, but it will properly handle cancellation (flatMapLatest is doing exactly what I wrote but without coroutineScope since it doesn't need an access to it)
👍 1
if you stick to flatMapLatest, I'm afraid you will have to wrap it to one more
flow {}
+
coroutineScope { }
:
flow.flatMapLatest { flowValue -> 
  flow {
     coroutineScope { 
        emitAll(stateFlowDependingOnFlowValue(flow1Value,scope))
     }
  }
}
b

benkuly

01/17/2022, 2:34 PM
Thank you very much, the solution with
transformLatest
seems to be perfect :)
👍 1