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

bookCoroutine Builders: launch and async

Svep för att visa menyn

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

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?

Vänligen välj det korrekta svaret

Var allt tydligt?

Hur kan vi förbättra det?

Tack för dina kommentarer!

Avsnitt 2. Kapitel 3

Fråga AI

expand

Fråga AI

ChatGPT

Fråga vad du vill eller prova någon av de föreslagna frågorna för att starta vårt samtal

Avsnitt 2. Kapitel 3
some-alt