Kotlin

launch and Jobs

admin by @admin ADMIN
1d ago
Jun 1, 2026
Public
0 0 up · 0 down Sign in to vote
`launch` starts a coroutine and returns a `Job` you can join, cancel, or check status on. Fire-and-forget or join-when-ready style.
Kotlin
Raw
import kotlinx.coroutines.*

suspend fun greet(name: String) {
    delay(50)
    println("hello $name")
}

fun main() = runBlocking {
    // Spawn 3 fire-and-forget coroutines
    val jobs = listOf("Alice", "Bob", "Cara").map { name ->
        launch { greet(name) }
    }

    // Wait for all of them
    jobs.joinAll()
    println("all done")

    // Cancel a still-running job
    val long = launch {
        repeat(100) { i ->
            delay(50)
            println("tick $i")
        }
    }
    delay(120)
    long.cancel()
    long.join()
    println("cancelled")
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.