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

ghedeon

11/07/2019, 1:11 PM
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

louiscad

11/07/2019, 1:29 PM
Using another coroutine scope: a custom one (
CoroutineScope(…)
), or
GlobalScope
g

ghedeon

11/07/2019, 2:52 PM
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

louiscad

11/07/2019, 3:02 PM
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

ghedeon

11/07/2019, 3:29 PM
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

louiscad

11/07/2019, 3:38 PM
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

ghedeon

11/07/2019, 4:02 PM
That did it. Thanks @louiscad!
3 Views