ir2pid
ir2pid

Reputation: 6126

Proper use of coroutines Dispatcher Main and Default

I'm trying to do a cup heavy calculation and then want to update the UI.

Below is my code:

private fun updateData() {
        GlobalScope.launch(Dispatchers.Default){ //work on default thread
            while (true){
                response.forEach {
                val out = doIntensiveWork()
                    withContext(Dispatchers.Main){ //update on main thread
                        _data.postValue(out)
                        delay(1500L)
                    }
                }
            }
        }
}

is this way of using coroutines okay? As running the entire work on Main also has no visible effect and work fine.

private fun updateData() {
        GlobalScope.launch(Dispatchers.Main){ //work on Main thread
            while (true){
                response.forEach {
                val out = doIntensiveWork()
                    _data.postValue(out)
                    delay(1500L)
                }
            }
        }
}

Which one is recommended?

Upvotes: 1

Views: 2612

Answers (1)

ChristianB
ChristianB

Reputation: 2680

You should avoid using GlobalScope for the reason described here and here.

And you should consider doing heavy computation off the main thread


suspen fun doHeavyStuff(): Result = withContext(Dispatchers.IO) { // or Dispatchers.Default
 // ...
}

suspend fun waitForHeavyStuf() = withContext(Dispatchers.Main) {
  val result = doHeavyStuff() // runs on IO thread, but results comes back on Main thread
  updateYourUI()
}

Documentation

Upvotes: 4

Related Questions