Skip to content

Instantly share code, notes, and snippets.

@alfonsogarsan
Last active July 21, 2020 08:54
Show Gist options
  • Save alfonsogarsan/412cec6503acc286633e276c28cf2ecd to your computer and use it in GitHub Desktop.
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
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
@alfonsogarsan
Copy link
Author

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment