Could I ask for some confirmation about this? I ha...
# coroutines
c
Could I ask for some confirmation about this? I have some flows calling `mapLatest`/
tranformLatest
etc, and I want to create a CoroutineScope that is cancelled when these flows are cancelled. So, roughly:
Copy code
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?
j
Could you please elaborate on what you're doing with the
scope
? 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.
c
Copy code
myFlow
  .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.)
It looks like what I’m trying to do is propagate cancellation via the coroutine context.
Copy code
myFlow
  .mapLatest {
    coroutineScope {
      SomeObject(
        state = anotherFlow.stateIn(this, ...)
      )
    }
  }
This would propagate cancellation but
mapLatest
will never emit, of course
I’m wondering if it’s possible to do what I’m trying to do
Oh, I could do
Copy code
myFlow
  .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 now
t
could you use flatMapLatest instead? I guess a lot of it depends on if the final item you're emitting needs to have a scope internally, or if this is for intermediary steps. Emitting an item bound to the flow's scope itself seems like bad practice
c
I think a slight refactoring would make use of
combine
and remove the StateFlow from “SomeObject” in the example code
I just haven’t gotten around to it