Junior — Middle
What experience do you have with applying coroutines in practice?
sobes.tech AI
Answer from AI
In practice, I have used coroutines to simplify asynchronous programming in Android applications. Main scenarios include:
- Performing network requests without blocking the main thread.
- Handling database operations in the background.
- Sequential execution of asynchronous tasks using suspend functions.
Example of using coroutines with Kotlin:
import kotlinx.coroutines.*
fun fetchData() {
GlobalScope.launch(Dispatchers.Main) {
val data = withContext(Dispatchers.IO) {
// Simulate network request
delay(1000)
"Request result"
}
println(data) // Output on main thread
}
}
This approach allows writing asynchronous code that looks synchronous, improving readability and maintainability.