Skip to content

Instantly share code, notes, and snippets.

@elvismetaphor
Last active August 2, 2021 04:57
Show Gist options
  • Save elvismetaphor/810712e3a08863c963c871f1bca0b3f2 to your computer and use it in GitHub Desktop.
Save elvismetaphor/810712e3a08863c963c871f1bca0b3f2 to your computer and use it in GitHub Desktop.
Try coroutines
import kotlinx.coroutines.experimental.*
fun main(args: Array<String>) {
val start = System.currentTimeMillis()
exampleBlocking()
val end = System.currentTimeMillis()
println("executing time: ${end - start}")
// Wait for async operations
Thread.sleep(3500)
}
fun printDelayed(message: String) {
Thread.sleep(1000)
println(message)
}
fun printNonBlocking(message: String) {
Thread {
Thread.sleep(1000)
println(message)
}.start()
}
suspend fun printDelayByCoroutine(message: String) {
delay(1000)
println(message)
}
suspend fun calculateResultAsync(number: Int): Int {
delay(1000)
return number * 100;
}
fun exampleBlocking() {
println("First")
printDelayed("Second")
println("Third")
}
fun exampleNonBocking() {
println("First")
printNonBlocking("Second")
println("Third")
}
fun exampleBlockingByCoroutine() {
println("First")
runBlocking {
printDelayByCoroutine("Second")
}
println("Third")
}
fun exampleNonBlockingByCoroutine() {
println("First")
launch {
printDelayByCoroutine("Second")
}
println("Third")
}
fun exampleDispatchByCoroutine() {
println("First - ${Thread.currentThread().name}")
launch(Dispatchers.IO) {
printDelayByCoroutine("Second - ${Thread.currentThread().name}")
}
println("Third - ${Thread.currentThread().name}")
}
fun exampleResult() = runBlocking {
val value1 = async {calculateResultAsync(1)}.await()
val value2 = async {calculateResultAsync(2)}.await()
val value3 = async {calculateResultAsync(3)}.await()
val sum = value1 + value2 + value3
println("blocking result: ${sum}")
}
fun exampleConcurrentResult() = runBlocking {
val value1 = async {calculateResultAsync(1)}
val value2 = async {calculateResultAsync(2)}
val value3 = async {calculateResultAsync(3)}
val sum = value1.await() + value2.await() + value3.await()
println("blocking result: ${sum}")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment