Skip to content

Instantly share code, notes, and snippets.

@booknara
Created July 17, 2023 22:17
Show Gist options
  • Save booknara/b464e9f961f7f2a2be1d8c324d1dccbb to your computer and use it in GitHub Desktop.
Save booknara/b464e9f961f7f2a2be1d8c324d1dccbb to your computer and use it in GitHub Desktop.
Launch vs Async in Kotlin Coroutines
package com.booknara.practice.kotlin.coroutine
import kotlinx.coroutines.async
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
fun main() {
// test_launch()
// test_async()
}
fun test_launch() {
runBlocking {
println("Before coroutine")
launch {
delay(1000)
println("Inside coroutine")
}
println("After coroutine")
}
}
fun test_async() {
runBlocking {
println("Before coroutine")
val deferred = async {
delay(1000)
return@async (1..10).random()
}
println("After coroutine")
println("Result: ${deferred.await()}")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment