Junior — Middle
Kuidas rakendada korutina oma projektis?
sobes.tech AI
Vastus AI-lt
In Android, coroutines are usually implemented using the Kotlin Coroutines library. To use coroutines, you need to add the dependency and use suspend functions together with CoroutineScope.
Example of a simple coroutine:
import kotlinx.coroutines.*
fun main() = runBlocking {
launch {
delay(1000L) // simulation of asynchronous work
println("Coroutine completed")
}
println("Starting coroutine")
}
In the 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 is created (for example, in a ViewModel), and coroutines are launched with the appropriate dispatcher (Dispatchers.IO for input/output, Dispatchers.Main for UI).