Junior — Middle
What methods can be used to initiate coroutine execution in Kotlin?
sobes.tech AI
Answer from AI
In Kotlin, a coroutine can be initiated in several ways, depending on the context and requirements:
- launch — starts a new coroutine without blocking the current thread, returns a Job. Used for background tasks.
GlobalScope.launch {
// code in coroutine
}
- async — starts a coroutine and returns a Deferred, which can be used to get the result asynchronously.
val deferred = GlobalScope.async {
// computation
42
}
val result = deferred.await()
- runBlocking — blocks the current thread until the coroutine completes, usually used in main or tests.
runBlocking {
// code
}
- withContext — switches the execution context within a coroutine, for example, to another dispatcher.
withContext(Dispatchers.IO) {
// input-output operation
}
The choice of method depends on whether you need to get a result, block the thread, or just run a task in the background.