#
GlobalScope.launch() Builder
This tutorial explains how we can use GlobalScope.launch()
method in order to start a coroutine in Kotlin.
This coroutine will run as a thread, in parallel with the main thread.
Info
GlobalScope.launch() method is considered a Coroutine Builder as it creates a coroutine.
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.GlobalScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
@SpringBootApplication
class Demo1Application
suspend fun main(args: Array<String>) {
runApplication<Demo1Application>(*args)
GlobalScope.launch {
println("START: Launch I")
delay(3000L)
println("Launch I - end")
}
GlobalScope.launch {
println("START: Launch II")
delay(2000L)
println("Launch II - end")
}
GlobalScope.launch {
println("START: Launch III")
delay(1000L)
println("Launch III - end")
}
println("END")
}
When we run this code we receive the following output:
END
START: Launch III
START: Launch I
START: Launch II
Launch III - end
Launch II - end
Launch I - end
Info
The starting order of the coroutines in this could change from one application run to another.