Junior — Middle
Can you explain the mechanism of coroutines and what are their advantages in asynchronous programming?
sobes.tech AI
Answer from AI
Coroutines are special functions that can suspend their execution and resume later, allowing for more readable and efficient asynchronous code.
In Android (Kotlin), coroutines enable long-running operations (such as network requests or database work) to be performed without blocking the main UI thread.
Advantages of coroutines:
- Easy to write asynchronous code that looks like synchronous code.
- Easy management of threads and task cancellation.
- Improved performance due to fewer threads being created.
Example of a coroutine in Kotlin:
import kotlinx.coroutines.*
fun main() = runBlocking {
launch {
delay(1000L)
println("Task completed")
}
println("Starting coroutine")
}