The launch coroutine builder lets you start a new task that runs in the background without blocking the main program. It helps you do many things at once easily.
Launch coroutine builder in Kotlin
launch(context) {
// code to run in coroutine
}launch starts a new coroutine immediately.
The context is optional and defines where the coroutine runs (like on the main thread or background).
launch {
println("Hello from coroutine!")
}launch(Dispatchers.IO) {
// Run blocking IO task here
}val job = launch { delay(1000L) println("Task done") } job.cancel()
This program starts a coroutine that waits half a second and then prints "World!" while the main coroutine prints "Hello," immediately. The delay at the end keeps the program running so we see both messages.
import kotlinx.coroutines.* fun main() = runBlocking { launch { delay(500L) println("World!") } println("Hello,") delay(1000L) // Wait to keep JVM alive }
launch returns a Job which you can use to cancel or check the coroutine.
Coroutines started with launch do not return a result. Use async if you need a result.
Always use runBlocking or another coroutine scope to keep the program alive when testing coroutines in main.
launch starts a new coroutine that runs independently.
It is useful for background tasks that do not return a value.
You can control and cancel coroutines using the Job returned by launch.