If i create a coroutineScope inside a flow which l...
# coroutines
r
If i create a coroutineScope inside a flow which launches In viewModelScope. Will the
coroutineScope
gets cancelled when the Job created from
viewmodelscope.launch
is cancelled ?
Copy code
init {
    a = viewModelScope.launch {
        abc()
    }
}

fun abc() = flow<Boolean> {
    val b = coroutineScope {
        // some operations
        emit(true)
    }
}

override fun onCleared() {
    super.onCleared()
    a.cancel()
}
When I do
a.cancel
will b be cancelled automatically ?
e
1.
flow()
is not designed for that, use
channelFlow()
instead
the way you've constructed it here, the scope inside flow is unrelated to viewModelScope, so no
r
Is it safe to pass the viewmodelscope inside function as parameter and then use that
e
if you want to change context inside the flow builder, use channelFlow
maybe take a moment to check, what are you trying to achieve?
r
So my basic use case is that I want the viewmodelScope inside the
flow {}
e
the (cold) flow builder should get dispatched on whatever it's collected on, but it doesn't have direct access to that scope
r
What if I use the channelFlow and start a new coroutine using
launch
inside channelFlow and then use the coroutineScope Will the coroutine scope inside launch will be same as the flow's coroutineScope (viewmodelScope)
e
it'll be a direct child of the viewmodelscope (not the same exact scope as it's a different job) but note that channelFlow closes when its builder returns, which launch() doesn't block
r
hmmm you are right What about the
producerScope
g
What are you trying to achieve? It’s not clear from your code, for example abc flow is never collected Also why do you need coroutineScope inside of flow?
k
You could write
abc().last()
and make flow run only once as a suspend function.
And
.last()
will cancel if viewModelScope gets canceled. You could create custom
CoroutineScope
and inject it into your ViewModel and use it. This way you'll be able to send that event when your ViewModel
onCleared
gets called.