1

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?

ir2pid
  • 5,604
  • 12
  • 63
  • 107

1 Answers1

4

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

ChristianB
  • 2,452
  • 2
  • 10
  • 22