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

bookCoroutine Builders: launch and async

Glissez pour afficher le menu

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?

Sélectionnez la réponse correcte

Tout était clair ?

Comment pouvons-nous l'améliorer ?

Merci pour vos commentaires !

Section 2. Chapitre 3

Demandez à l'IA

expand

Demandez à l'IA

ChatGPT

Posez n'importe quelle question ou essayez l'une des questions suggérées pour commencer notre discussion

Section 2. Chapitre 3
some-alt