Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Oppiskele Coroutine Builders: launch and async | Getting Started with Coroutines
Kotlin Concurrency Fundamentals

bookCoroutine Builders: launch and async

Pyyhkäise näyttääksesi valikon

When working with Kotlin coroutines, you often need to start concurrent tasks. Coroutine builders are special functions that launch new coroutines. The two most common builders are launch and async.

The launch builder is used for fire-and-forget operations: you start a coroutine, and it runs independently, without returning a result. This is ideal for operations like updating the UI or logging, where you do not need to capture a value.

The async builder, on the other hand, is used when you want your coroutine to compute and return a result. It returns a Deferred object, which you can use to retrieve the result with the await() function. This makes async suitable for concurrent computations or any situation where you need to gather results from multiple coroutines.

Main.kt

Main.kt

copy
12345678910111213141516171819202122232425
package com.example import kotlinx.coroutines.* fun main() = runBlocking { // Using launch for fire-and-forget val job = launch { println("Launch: Starting background work") delay(500) println("Launch: Work done") } // Using async for returning a result val deferred = async { println("Async: Calculating result") delay(1000) 42 // This value will be returned } // Wait for launch job to finish job.join() // Get the result from async val result = deferred.await() println("Async: Result is $result") }

Choosing between launch and async depends on your needs. Use launch when you simply want to start a coroutine that performs an action but does not return a value. This is common for updating the UI, sending analytics, or any background work where you do not need a result. Use async when you need to perform a task concurrently and obtain a result from it. You can start multiple async coroutines and then collect their results using await(), which is especially useful for parallel computations or aggregating data from multiple sources. Remember, if you start a coroutine with async but never call await(), the result is lost and any exceptions may be ignored, so use it only when you really need the result.

question mark

Which coroutine builder should you use when you need a result from a coroutine?

Select the correct answer

Oliko kaikki selvää?

Miten voimme parantaa sitä?

Kiitos palautteestasi!

Osio 2. Luku 3

Kysy tekoälyä

expand

Kysy tekoälyä

ChatGPT

Kysy mitä tahansa tai kokeile jotakin ehdotetuista kysymyksistä aloittaaksesi keskustelumme

Osio 2. Luku 3
some-alt