#
async Builder
This tutorial explains how we can use async
in order to start a coroutine in Kotlin.
Info
- async is considered a Coroutine Builder as it creates a coroutine.
- async builder is similar to launch, but async will return also a value. This value is returned by a lambda expression.
Take a look at the following example created with Spring Boot 3.0, maven in Kotlin:
Demo1Application.java
package com.example.demo1
import kotlinx.coroutines.*
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
@SpringBootApplication
class Demo1Application
suspend fun main(args: Array<String>) {
runApplication<Demo1Application>(*args)
println("START")
val valueReturned1 = GlobalScope.async {
println("START: valueReturned1")
delay(3000L)
"My value returned 1"
}
val valueReturned2 = GlobalScope.async {
println("START: valueReturned2")
delay(2000L)
"My value returned 2"
}
val valueReturned3 = GlobalScope.async {
println("START: valueReturned3")
delay(1000L)
"My value returned 3"
}
println(valueReturned1.await())
println(valueReturned2.await())
println(valueReturned3.await())
println("END")
}
When we run this code we receive the following output:
START
START: valueReturned1
START: valueReturned3
START: valueReturned2
My value returned 1
My value returned 2
My value returned 3
END
Info
- The "async" coroutines are started in a random manner (but almost in the same time).
await()
method is waiting for the value to be returned.println(valueReturned1.await())
,println(valueReturned2.await())
,println(valueReturned3.await())
run sequentially.