Junior — Middle
What methods of task execution in Coroutines do you know?
sobes.tech AI
Answer from AI
In Kotlin Coroutines, tasks can be performed in several ways:
-
launch — starts a new coroutine that runs concurrently and does not return a result. Used for background tasks where no result is needed.
-
async — starts a coroutine that returns a result as a Deferred, allowing you to get the result via await(). Suitable for parallel computations with a result.
-
runBlocking — blocks the current thread until the coroutine completes, often used in main functions or tests.
-
withContext — switches the execution context (for example, to Dispatchers.IO for input/output operations) and executes a block of code, returning a result.
Example:
import kotlinx.coroutines.*
fun main() = runBlocking {
launch {
delay(1000)
println("Task in launch")
}
val result = async {
delay(500)
42
}
println("Result of async: ${result.await()}")
}