Last active
July 21, 2020 08:54
-
-
Save alfonsogarsan/412cec6503acc286633e276c28cf2ecd to your computer and use it in GitHub Desktop.
This is a little example of how to compose two coroutines (IO) to work concurrently and to make parent coroutine to suspend in await calls
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import kotlinx.coroutines.* | |
fun main() { | |
GlobalScope.launch { | |
println("[${Thread.currentThread().name}] Before asyncs") | |
val one = async (Dispatchers.IO) { doSomething1() } | |
val two = async (Dispatchers.IO) { doSomething2() } | |
println("[${Thread.currentThread().name}] After asyncs") | |
println("[${Thread.currentThread().name}] The answer is ${one.await() + two.await()}") | |
println("[${Thread.currentThread().name}] After awaits") | |
} | |
println("[${Thread.currentThread().name}] Sleeping before exiting...") | |
Thread.sleep(2000L) | |
println("[${Thread.currentThread().name}] Exit") | |
} | |
suspend fun doSomething1(): Int { | |
delay(100L) // pretend we are doing something useful here | |
println("[${Thread.currentThread().name}] doSomething1") | |
return 13 | |
} | |
suspend fun doSomething2(): Int { | |
delay(1000L) // pretend we are doing something useful here, too | |
println("[${Thread.currentThread().name}] doSomething2") | |
return 29 | |
} | |
//Output executing program in Kotlin Playground https://play.kotlinlang.org/ | |
//OUTPUT | |
//[main] Sleeping before exiting... | |
//[DefaultDispatcher-worker-1] Before asyncs | |
//[DefaultDispatcher-worker-1] After asyncs | |
//[DefaultDispatcher-worker-2] doSomething1 | |
//[DefaultDispatcher-worker-1] doSomething2 | |
//[DefaultDispatcher-worker-1] The answer is 42 | |
//[DefaultDispatcher-worker-1] After awaits | |
//[main] Exit |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is a little example of how to compose two coroutines (IO) to work concurrently and to make parent coroutine to suspend in await calls