Johann
Johann

Reputation: 29867

Updating the UI after the background work completes in a coroutine

I came across the following code sample that shows how to use a coroutine to run your background code on the IO thread and then switch to the UI (Main) thread when you need to update the UI:

class YourActivity : CoroutineScope {
    private lateinit var job: Job

    // context for io thread
    override val coroutineContext: CoroutineContext
        get() = Dispatchers.IO + job

    override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

    job = Job()
  }

    fun toDoSmth() {
        launch {
            // task, do smth in io thread
            withContext(Dispatchers.Main) {
              // do smth in main thread after task is finished
            }                  
        }
    }

   override fun onDestroy() {
      job.cancel()
      super.onDestroy()
   }
}

Is this the correct way to update the UI after the background work has completed?

Upvotes: 1

Views: 1414

Answers (1)

Valeriy Katkov
Valeriy Katkov

Reputation: 40602

Actually, the things are much easier. You shouldn't manage your own coroutine scope, take a look at LifecycleScope, it's already bound to the activity lifecycle. But the better way is to use ViewModelScope in conjunction with ViewModel library.

Note, that both viewModelScope and lifecycleScope use Dispatchers.Main by default, so you should pass IO dispatcher to the launch method, like:

viewModelScope.launch(Dispatchers.IO) {
    // task, do smth in io thread
    withContext(Dispatchers.Main) {
      // do smth in main thread after task is finished
    }
}

Upvotes: 7

Related Questions