Skip to content

Instantly share code, notes, and snippets.

@andreas-kkday
Last active July 8, 2022 04:44
Show Gist options
  • Save andreas-kkday/59f4183e320fddc08ac92980cd739992 to your computer and use it in GitHub Desktop.
Save andreas-kkday/59f4183e320fddc08ac92980cd739992 to your computer and use it in GitHub Desktop.
Coroutine Async
lifecycleScope.launch(Dispatchers.IO) {
val start = Instant.now().epochSecond
println(">>> ${Instant.now().epochSecond}")
val def1 = async { async1() }
val def2 = async { async2() }
println(">>> ${def1.await()} ${def2.await()}")
println(">>> ${Instant.now().epochSecond - start}") //3
}
lifecycleScope.launch() {
val start = Instant.now().epochSecond
println(">>> ${Instant.now().epochSecond}")
val def1 = async { async1() }
val def2 = async { async2() }
println(">>> ${def1.await()} ${def2.await()}")
println(">>> ${Instant.now().epochSecond - start}") //6
}
lifecycleScope.launch(Dispatchers.Main) {
val start = Instant.now().epochSecond
println(">>> ${Instant.now().epochSecond}")
val def1 = async { async1() }
val def2 = async { async2() }
println(">>> ${def1.await()} ${def2.await()}")
println(">>> ${Instant.now().epochSecond - start}") //6
}
lifecycleScope.launch(Dispatchers.Unconfined) {
val start = Instant.now().epochSecond
println(">>> ${Instant.now().epochSecond}")
val def1 = async { async1() }
val def2 = async { async2() }
println(">>> ${def1.await()} ${def2.await()}")
println(">>> ${Instant.now().epochSecond - start}") //6
}
private fun async1(): Thread {
Thread.sleep(3 * 1000)
return Thread.currentThread()
}
private fun async2(): Thread {
Thread.sleep(3 * 1000)
return Thread.currentThread()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment