Sobes.tech
Junior — Middle

Kuidas saab korutinade abil samaaegselt täita mitut ülesannet?

sobes.tech AI

Vastus AI-lt

To execute multiple tasks simultaneously using coroutines in Kotlin, you can use:

  • launch — starts a new coroutine that runs in parallel with others.
  • async — starts a coroutine that returns a result via Deferred.

Example of starting two tasks simultaneously and waiting for their results:

import kotlinx.coroutines.*

fun main() = runBlocking {
    val job1 = async {
        delay(1000)
        "Result of task 1"
    }
    val job2 = async {
        delay(500)
        "Result of task 2"
    }

    // Wait for both results
    val result1 = job1.await()
    val result2 = job2.await()

    println(result1)
    println(result2)
}

This way, coroutines make it easy to start multiple tasks in parallel and synchronize their results.