Skip to content

Instantly share code, notes, and snippets.

@houssemzaier
Created August 10, 2020 10:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save houssemzaier/74fd025c6aba01ea477c620c44fd2fa0 to your computer and use it in GitHub Desktop.
Save houssemzaier/74fd025c6aba01ea477c620c44fd2fa0 to your computer and use it in GitHub Desktop.
import kotlinx.coroutines.async
import kotlinx.coroutines.delay
import kotlinx.coroutines.runBlocking
fun main() {
runBlocking {
val doIt1 = doIt1()
val doIt2 = doIt2()
val doIt3 = doIt3()
println("result ${doIt1 + doIt2 + doIt3}")
/**
doIt1 started
doIt1 finished
doIt2 started
doIt2 finished
doIt3 started
doIt3 finished
result 6
*/
}
runBlocking {
val doIt1 = async { doIt1() }
val doIt2 = async { doIt2() }
val doIt3 = async { doIt3() }
println("result ${doIt1.await() + doIt2.await() + doIt3.await()}")
/**
doIt1 started
doIt2 started
doIt3 started
doIt3 finished
doIt2 finished
doIt1 finished
result 6
*/
}
}
suspend fun doIt1(): Int {
println("doIt1 started")
delay(5000)
println("doIt1 finished")
return 1
}
suspend fun doIt2(): Int {
println("doIt2 started")
delay(2000)
println("doIt2 finished")
return 2
}
suspend fun doIt3(): Int {
println("doIt3 started")
delay(1000)
println("doIt3 finished")
return 3
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment