Junior — Middle
How to perform an asynchronous function and get its result using Coroutines?
sobes.tech AI
Answer from AI
In Android, the Kotlin Coroutines library is used to perform asynchronous operations with coroutines. To call an asynchronous function and get its result, you need to:
- Define the function as
suspend. - Launch a coroutine in an appropriate context (e.g., in
viewModelScopeorlifecycleScope). - Use
awaitor simply call the function inside the coroutine to get the result.
Example:
import kotlinx.coroutines.*
// Asynchronous suspend function
suspend fun fetchData(): String {
delay(1000) // simulate a long operation
return "Data result"
}
fun main() = runBlocking {
// Launch coroutine and get result
val result = fetchData()
println(result) // Will output: Data result
}
In Android, lifecycleScope is usually used in an Activity or Fragment:
lifecycleScope.launch {
val data = fetchData()
// update UI with the received data
}
Thus, coroutines allow writing asynchronous code sequentially and conveniently obtaining results.