Coroutine Builders: launch and async
Scorri per mostrare il 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
12345678910111213141516171819202122232425package 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.
Grazie per i tuoi commenti!
Chieda ad AI
Chieda ad AI
Chieda pure quello che desidera o provi una delle domande suggerite per iniziare la nostra conversazione