Coroutine
A coroutine is a concurrency design pattern used in programming that allows for writing asynchronous code in a sequential manner. In Android development, coroutines are primarily used with Kotlin to simplify asynchronous programming and manage background tasks efficiently.
Characteristics
– Lightweight: Coroutines are lighter than threads; thousands of coroutines can run on a single thread without significant overhead.
– Suspension: Coroutines can be paused and resumed, allowing for non-blocking execution of code. This means that a coroutine can wait for a long-running task to complete without blocking the main thread.
– Structured Concurrency: Coroutines are designed to be structured, meaning they can be easily managed and canceled, reducing the risk of memory leaks and other issues.
– Integration with Kotlin: Coroutines are built into the Kotlin language, providing a seamless way to handle asynchronous programming.
Examples
– Basic Coroutine Usage:
kotlin
GlobalScope.launch {
// This code runs in a coroutine
delay(1000L) // Non-blocking delay for 1 second
println("Hello from coroutine!")
}
-
Using Coroutines with ViewModel:
“`kotlin
class MyViewModel : ViewModel() {
private val _data = MutableLiveData()
val data: LiveDataget() = _data fun fetchData() {
viewModelScope.launch {
val result = fetchDataFromNetwork() // Suspend function
_data.value = result
}
}
}
“` -
Error Handling in Coroutines:
kotlin
GlobalScope.launch {
try {
val result = riskyOperation() // May throw an exception
} catch (e: Exception) {
println("Error occurred: ${e.message}")
}
}


