https://kotlinlang.org logo
Title
r

Ravin Jain

10/29/2021, 1:00 AM
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 ?
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

ephemient

10/29/2021, 1:08 AM
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

Ravin Jain

10/29/2021, 1:12 AM
Is it safe to pass the viewmodelscope inside function as parameter and then use that
e

ephemient

10/29/2021, 1:12 AM
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

Ravin Jain

10/29/2021, 1:18 AM
So my basic use case is that I want the viewmodelScope inside the
flow {}
e

ephemient

10/29/2021, 1:18 AM
the (cold) flow builder should get dispatched on whatever it's collected on, but it doesn't have direct access to that scope
r

Ravin Jain

10/29/2021, 1:25 AM
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

ephemient

10/29/2021, 1:29 AM
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

Ravin Jain

10/29/2021, 1:40 AM
hmmm you are right What about the
producerScope
g

gildor

10/29/2021, 4:56 AM
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

K Merle

10/29/2021, 5:56 AM
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.