Hey everyone, I want to make the second version of...
# coroutines
a
Hey everyone, I want to make the second version of the code run in parallel do you have any ideas, how to achieve it?
Copy code
fun getAll(): Flow<...> { //works in parallel, doesn't respect structural concurrency
    GlobalScope.launch {
        //start request...
    }
    return db.flow()//starts emitting immediately...
}

suspend fun getAll(): Flow<...> { //works sequentially
    withContext(<http://Dispatchers.IO|Dispatchers.IO>) {
        launch {
            //start request...
        }
    }
    return db.flow()//start emitting after request is finished...
}
d
second version of what code? Not sure what you're trying to achieve.
a
I meant second version of the function. The launch courutine, which executes request, runs sequentially and
db.flow()
starts emitting only after request finished.
d
Copy code
fun getAll(): Flow<...> = flow { //works sequentially
    withContext(<http://Dispatchers.IO|Dispatchers.IO>) {
        //start request...
    }
    emitAll(db.flow())//start emitting after request is finished...
}
a
no, this one also waits until request will be executed
I want to subscribe to db immediately, and then execute network request. I'm not fully understand why second version of the function doesn't run in parallel. Because semantiacally it looks very similar 🤔
d
Copy code
fun getAll(): Flow<...> = flow { //works in parallel, but only once flow is collected
    coroutineScope {
        launch(<http://Dispatchers.IO|Dispatchers.IO>) {
            //start request...
        }
        emitAll(db.flow()) //starts emitting immediately...
    }
}
The second version doesn't run in parallel because
withContext
waits for the
launch
to finish because Structured Concurrency.
a
Thanks Dominic, this one works, I wasn't aware of
courutineScope
function. I expected that everything which is launched with different Dispatcher would be executed in parallel.
a
launch != withContext - launch starts something in parallel, withContext starts something and suspends until it has completed. Regardless of the dispatcher used to actually execute bits of it. (and the coroutineScope here enforces that both have completed)