Sobes.tech
Junior — Middle

Milliste meetoditega saab teie tehnoloogiate virnas korutina täitmise algatada?

sobes.tech AI

Vastus AI-lt

In Android, the following methods are commonly used to start coroutines:

  • launch — starts a new coroutine without waiting for the result, often used for background tasks.
  • async — starts a coroutine and returns a Deferred, which can be used to get the result later.
  • runBlocking — blocks the current thread until the coroutine completes, rarely used, mainly in tests or main functions.

Example of starting a coroutine in ViewModel:

viewModelScope.launch {
    val data = repository.loadData()
    // update UI
}

Here, viewModelScope will automatically cancel the coroutine when the ViewModel is destroyed.