Junior — Middle
What is the main role of coroutines in programming and how do they differ from threads?
sobes.tech AI
Answer from AI
Coroutines are lightweight threads of execution that allow writing asynchronous and concurrent code in a simpler and more understandable way. In Android (and Kotlin), coroutines are used to perform background tasks without blocking the main thread (UI thread).
Main differences between coroutines and threads:
- Lightweight: coroutines consume much fewer resources than system threads.
- Management: coroutines are managed by a scheduler within the application, not by the operating system.
- Suspension and resumption: coroutines can be suspended at certain points (suspend) and resumed, simplifying asynchronous programming.
Example of using a coroutine in Kotlin for Android:
import kotlinx.coroutines.*
fun loadData() {
GlobalScope.launch(Dispatchers.Main) { // launch a coroutine on the main thread
val data = withContext(Dispatchers.IO) { // switch to background thread
fetchDataFromNetwork() // long request
}
updateUI(data) // update UI
}
}
Thus, coroutines allow writing asynchronous code that looks sequential, without complex callbacks and blocking.