Junior — Middle
What constructs do you know for creating coroutines outside of main functions?
sobes.tech AI
Answer from AI
In Kotlin for Android, coroutines can be created not only in main functions but also using various constructs:
-
launch — starts a new coroutine without a return result, usually within a
CoroutineScope. -
async — starts a coroutine that returns a result via
Deferred. -
runBlocking — blocks the current thread, waiting for the coroutine to finish (commonly used in tests or main).
-
withContext — switches the execution context within a coroutine, for example, to
Dispatchers.IO.
Example of creating a coroutine outside the main function:
fun fetchData(scope: CoroutineScope) {
scope.launch {
val data = async { loadDataFromNetwork() }.await()
println(data)
}
}
suspend fun loadDataFromNetwork(): String {
// simulating a network request
delay(1000)
return "Data"
}
Thus, coroutines can be created using launch, async, and withContext to switch contexts, as well as combining these constructs for efficient asynchronous code.