#
runBlocking Builder
This tutorial explains how we can use runBlocking
in order to start a coroutine in Kotlin.
Info
- runBlocking is considered a Coroutine Builder as it creates a coroutine.
- This new created coroutine will stop the current thread for running all we have defined inside it. When the coroutine will complete, the main thread will continue normally. This coroutine behaviour is atypical for a coroutine which run in parallel with the thread.
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.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
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")
runBlocking {
println("START: runBlocking I")
launch {
delay(2000L)
println(">>>>>>>>>>>> runBlocking I >> launch 1")
}
launch {
delay(1000L)
println(">>>>>>>>>>>> runBlocking I >> launch 2")
}
println("runBlocking I - end")
}
println("END")
}
When we run this code we receive the following output:
START
START: runBlocking I
runBlocking I - end
>>>>>>>>>>>> runBlocking I >> launch 2
>>>>>>>>>>>> runBlocking I >> launch 1
END
Info
If instead launch
method we will use GlobalScope.launch
the execution behaviour will change as the new coroutine
will have another scope.