Created
January 30, 2021 18:13
-
-
Save GauravChaddha1996/ae7804f756fbf2c0118a11bf8c34465a to your computer and use it in GitHub Desktop.
This file contains 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
fun main() { | |
runBlocking { | |
val coroutineX = GlobalScope.launch { | |
val result1 = n1(5) | |
println("Hello I'll print after n1 is over") | |
println("Result1: $result1") | |
val result2 = n2(5) | |
println("Hello I'll print after n2 is over") | |
println("Result2: $result2") | |
} | |
coroutineX.join() | |
} | |
} | |
suspend fun n1(a: Int): Int { | |
delay(500) | |
return a | |
} | |
suspend fun n2(a: Int): Int { | |
val coroutineY = GlobalScope.async (Dispatchers.IO) { | |
// same as Thread.sleep() but for coroutines | |
delay(500) | |
return@async a*a | |
} | |
return coroutineY.await() | |
} | |
/* | |
OUTPUT: | |
Hello I'll print after n1 is over | |
Result1: 5 | |
Hello I'll print after n2 is over | |
Result2: 25 | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment