Sobes.tech
Junior — Middle

What methods can be used to initiate coroutine execution in your technology stack?

sobes.tech AI

Answer from AI

In Android, the following methods are usually used to run 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, used rarely, mainly in tests or main functions.

Example of starting a coroutine in ViewModel:

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

Here, viewModelScope automatically cancels the coroutine when the ViewModel is destroyed.