Junior — Middle
What is the main purpose and function of coroutines in programming?
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. The main goal of coroutines is to simplify the management of parallelism and asynchrony without complex callbacks or threads.
In Android (and Kotlin), coroutines enable performing long-running operations (such as network requests, database work) without blocking the main UI thread, while maintaining a simple and sequential style of code.
Example of a coroutine in Kotlin:
import kotlinx.coroutines.*
fun main() = runBlocking {
launch {
delay(1000L)
println("Hello from coroutine!")
}
println("Hello from main")
}
Here, launch starts a coroutine that suspends for 1 second without blocking the main thread.