does collecting two flows inside the same coroutin...
# coroutines
r
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
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
collect
is a suspend function so it suspends until
flow1
finishes. It’s always better to use
onEach
+
launchIn
combination
no red 1
r
can you provide a snippet how would you do this
k
Copy code
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:
Copy code
flow1.onEach {

}.launchIn(viewModelScope)

flow2.onEach {

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

    }
    flow2.collect {

    }
}
flow2.collect
will be called only after
flow1
finished
r
thnx, and does the fact you're using a `Job`or `SupervisorJob`for the context play a role in the outcome?
k
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
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
thnx for your explanation