We can use the Job#join()
suspend function to await the completion of the coroutine.
Observe the following program :
private val client = HttpClient(CIO)
fun main() {
runBlocking {
launch {
println("response = ${getMathFact(1)}")
}
println("Execution complete!")
}
}
private suspend fun getMathFact(num: Int): String {
println("sending R#$num...")
return client.get("http://numbersapi.com/$num/math").bodyAsText()
}
/* Output :
Execution complete!
sending R#1...
response = 1 is the first figurate number of every kind, such as triangular number, pentagonal number and centered hexagonal number, to name just a few.
*/
In the output, note that Execution complete!
is printed even before sending the request! This is because launch is a non-blocking function that returns immediately and does not wait for the coroutine to finish. To wait for the coroutine to finish, we can use the Job#join()
function :
private val client = HttpClient(CIO)
fun main() {
runBlocking {
val job = launch {
println("response = ${getMathFact(1)}")
}
job.join()
println("Execution complete!")
}
}
private suspend fun getMathFact(num: Int): String {
println("sending R#$num...")
return client.get("http://numbersapi.com/$num/math").bodyAsText()
}
/* Output :
sending R#1...
response = 1 is also the first and second numbers in the Fibonacci sequence and is the first number in many other mathematical sequences.
Execution complete!
*/
Now the line Execution complete!
is printed after completion because join()
function awaits coroutine to finish.