Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Impara Async/Await for Parallel Tasks | Advanced Coroutine Patterns
Kotlin Concurrency Fundamentals

bookAsync/Await for Parallel Tasks

Scorri per mostrare il menu

When you have several independent tasks that can run at the same time, you want to avoid waiting for each one to finish before starting the next. The async/await pattern in Kotlin coroutines lets you launch multiple tasks in parallel, then efficiently collect their results when all are done. This approach is especially useful for tasks like fetching data from different sources or performing calculations that do not depend on each other. With async, you start a coroutine that returns a Deferred object, which represents a future result. You then use await() to suspend and wait for the result when you need it, without blocking the thread.

Main.kt

Main.kt

copy
12345678910111213141516171819202122232425262728
package com.example import kotlinx.coroutines.* import kotlin.system.measureTimeMillis suspend fun fetchFirstData(): String { delay(1000L) return "First Result" } suspend fun fetchSecondData(): String { delay(1200L) return "Second Result" } fun main() = runBlocking { val time = measureTimeMillis { val firstDeferred = async { fetchFirstData() } val secondDeferred = async { fetchSecondData() } // Both fetches run in parallel. val first = firstDeferred.await() val second = secondDeferred.await() println("Results: $first, $second") } println("Completed in $time ms") }

By using async, you run both fetchFirstData() and fetchSecondData() at the same time, rather than one after the other. This means the total time taken is roughly as long as the slower of the two tasks, instead of the sum of both durations. The await() function suspends the coroutine until the result is ready, but does not block the underlying thread, allowing other work to continue. This pattern is ideal for improving performance when you have several independent operations that can be done in parallel, such as making multiple network requests or processing large datasets.

question mark

What does the await() function do in Kotlin coroutines?

Select the correct answer

Tutto è chiaro?

Come possiamo migliorarlo?

Grazie per i tuoi commenti!

Sezione 3. Capitolo 2

Chieda ad AI

expand

Chieda ad AI

ChatGPT

Chieda pure quello che desidera o provi una delle domande suggerite per iniziare la nostra conversazione

Sezione 3. Capitolo 2
some-alt