Created
August 10, 2020 10:01
-
-
Save houssemzaier/74fd025c6aba01ea477c620c44fd2fa0 to your computer and use it in GitHub Desktop.
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.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