Async/Await for Parallel Tasks
Svep för att visa menyn
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
12345678910111213141516171819202122232425262728package 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.
Tack för dina kommentarer!
Fråga AI
Fråga AI
Fråga vad du vill eller prova någon av de föreslagna frågorna för att starta vårt samtal