Junior — Middle
How to implement a coroutine in your project?
sobes.tech AI
Answer from AI
In Android, coroutines are usually implemented using the Kotlin Coroutines library. To use coroutines, you need to add a dependency and use suspend functions along with CoroutineScope.
Example of a simple coroutine:
import kotlinx.coroutines.*
fun main() = runBlocking {
launch {
delay(1000L) // simulate asynchronous work
println("Coroutine completed")
}
println("Starting coroutine")
}
In a project, coroutines are used to perform background tasks without blocking the main thread, such as loading data from the network or working with a database. For this, a CoroutineScope (for example, in a ViewModel) is created and coroutines are launched with the appropriate dispatcher (Dispatchers.IO for input/output, Dispatchers.Main for UI).