https://kotlinlang.org logo
Title
r

Remy Benza

03/22/2021, 9:28 AM
does collecting two flows inside the same coroutineScope influence each other when the coroutine context is a
SupervisorJob
?
example:
val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main)
scope.launch {
flow1.collect { //code  }
flow2.collect { //code  }
}
if the collection of flow1 fails? does flow2 run normally? I think I would because of the SupervisorJob context. But I've experience flow2 does not get collected.
n

Natsuki(开元米粉实力代购)

03/22/2021, 9:36 AM
there's nothing to do with
SupervisorJob
, that's becoz in semantic flow is cold, thus when runs
flows2.collect
that indicate
flow1.collect
is done, use
launchIn
or fire another
launch
with each collect
k

KamilH

03/22/2021, 9:47 AM
collect
is a suspend function so it suspends until
flow1
finishes. It’s always better to use
onEach
+
launchIn
combination
:no_red: 1
r

Remy Benza

03/22/2021, 9:48 AM
can you provide a snippet how would you do this
k

KamilH

03/22/2021, 9:51 AM
flow1.onEach { 
    // handle new value here
}.launchIn(scope)

scope.launch { 
    flow1.collect { 
        // handle new value here
    }
}
These two are doing the same - lets you launch new coroutine and collect items
The difference is that you can do this:
flow1.onEach {

}.launchIn(viewModelScope)

flow2.onEach {

}.launchIn(viewModelScope)
without waiting for flow1 to finish, while here:
viewModelScope.launch {
    flow1.collect {

    }
    flow2.collect {

    }
}
flow2.collect
will be called only after
flow1
finished
r

Remy Benza

03/22/2021, 9:59 AM
thnx, and does the fact you're using a `Job`or `SupervisorJob`for the context play a role in the outcome?
k

KamilH

03/22/2021, 10:03 AM
In this context no. If I’m not mistaken it would make a difference only when one of them (collections) throw an exception. In
Job
case whole job would be cancelled while in
SupervisorJob
it wouldn’t
d

dewildte

03/22/2021, 1:41 PM
Here you have two flows in a single coroutine. If there is an uncaught exception thrown then the coroutine it is in will be canceled and then the scope the coroutine is in will also be canceled. If the scope has a
SupervisorJob
then the scope will not be canceled.
As for the collection of the two flows influencing the other, the answer is yes if they are collected in the same coroutine.
.collect
does not start a new coroutine, it just suspends the current coroutine until the collection is complete.
r

Remy Benza

03/22/2021, 3:00 PM
thnx for your explanation