Skip to content

Instantly share code, notes, and snippets.

@GauravChaddha1996
Created January 30, 2021 18:13
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 GauravChaddha1996/ae7804f756fbf2c0118a11bf8c34465a to your computer and use it in GitHub Desktop.
Save GauravChaddha1996/ae7804f756fbf2c0118a11bf8c34465a to your computer and use it in GitHub Desktop.
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