Chris Fillmore
07/17/2023, 5:29 PMtranformLatest
etc, and I want to create a CoroutineScope that is cancelled when these flows are cancelled. So, roughly:
myFlow
.mapLatest {
val scope = CoroutineScope(currentCoroutineContext().job)
// returns something that uses `scope`
}
So, my expectation is that when myFlow
emits, scope
will be cancelled. That’s correct?Joffrey
07/17/2023, 5:31 PMscope
? From just this snippet, I see no reason why the flow or the mapLatest
operator would be aware of this scope, and thus no way it could possibly cancel it. So I guess what follows matters.Chris Fillmore
07/17/2023, 5:37 PMmyFlow
.mapLatest {
val scope = CoroutineScope(currentCoroutineContext().job)
return SomeObject(
state = anotherFlow.stateIn(scope, ...)
)
}
// elsewhere, in my UI
val someObjectState by someObject.state.collectAsState()
Something like this. A StateFlow is collected in that scope.
(P.S. I don’t love this but it’s some older code and it’s how I did it.)Chris Fillmore
07/17/2023, 5:40 PMChris Fillmore
07/17/2023, 5:42 PMmyFlow
.mapLatest {
coroutineScope {
SomeObject(
state = anotherFlow.stateIn(this, ...)
)
}
}
This would propagate cancellation but mapLatest
will never emit, of courseChris Fillmore
07/17/2023, 5:42 PMChris Fillmore
07/17/2023, 5:56 PMmyFlow
.transformLatest {
coroutineScope {
emit(Someobject(
state = anotherFlow.stateIn(this, ...)
))
}
}
Sorry I know this is ugly as sin but I don’t have the bandwidth to fix all this right nowTrevor Stone
07/17/2023, 6:06 PMChris Fillmore
07/17/2023, 6:07 PMcombine
and remove the StateFlow from “SomeObject” in the example codeChris Fillmore
07/17/2023, 6:07 PM