https://kotlinlang.org logo
#coroutines
Title
# coroutines
t

Tim Malseed

06/08/2021, 3:27 AM
I keep making this mistake:
Copy code
CoroutineScope.launch {
    stateFlowA.collect {
        foo()
    }
    stateFlowB.collect {
        bar()
    }
}
And wondering why bar() isn't called. (It's because stateFlowA never completes, as it's a StateFlow). I think I'm just tempted to declare both suspend functions inside the one
CoroutineScope.launch { }
block out of convenience. Anyway, the simple solution is to just not make this mistake. But I wonder if I'm doing this because there's a problem with my mental model. I think maybe this comes about because
launch{}
is the only operator I ever use to kick-off a suspend fun (I rarely consider
async
, and I'm not sure if there are others. I don't have a specific question, just wanted to discuss this and see if anyone else has the same problem. I'm hoping the discussion will help correct my mental model.
g

gildor

06/08/2021, 4:30 AM
I would say that almost in all cases you shouldn’t use collect for such cases and instead use onEach().launchIn(scope)
2
t

Tim Malseed

06/08/2021, 4:40 AM
Oh yeah, that's a little nicer, and definitely helps avoid this mistake
3 Views