When running with `Dispatchers.Main.immediate`, wh...
# coroutines
g
When running with
Dispatchers.Main.immediate
, what is the the best way to execute a portion immediately and
launchAndForget
the rest? Ex:
Copy code
suspended fun foo(){
    operationA()  // <--- don't wait for it, it's on IO
    operationB() // <--- post on Main immediately
}
It already works if I swap the order, like
Copy code
operationB() // <--- post on Main immediately
    operationA()  // <--- don't wait for it, it's on IO
But I'm looking for a way that doesn't depend on the order of operations.
l
Using another coroutine scope: a custom one (
CoroutineScope(…)
), or
GlobalScope
g
Hmm, not sure if I got the idea. Ex:
Copy code
launch(Dispatchers.Main.immediate){
        operationA() // IO stuff
        operationB() // immediate stuff
}
How to make
operationB()
to post on main immediately? Wrap the
operationA
in another coroutine scope? Didn't work unfortunately
l
Use
launch
to not wait for the completion of a child coroutine
You can also take advantage of
start = CoroutineStart.UNDISPATCHED
as a parameter of
launch
.
g
Copy code
GlobalScope.launch(Dispatchers.Main.immediate) {
            coroutineScope {
                launch(start = CoroutineStart.UNDISPATCHED, context = <http://Dispatchers.IO|Dispatchers.IO>) {
                    delay(1000)
                    println("third")
                }
            }
            println("first")
        }
        println("second")
This prints
second third first
l
Yes, because the local coroutineScope waits for its children
Your use case is about breaking structuring concurrency, so you want a scope like
CoroutineScope(<http://Dispatchers.IO|Dispatchers.IO>)
g
That did it. Thanks @louiscad!