Why does my app not crash after updating a textview within a IO scope?

Viewed 36

So, I'm kind of confused right now.

I have a small Android App that is using Kotlin Coroutines. I know we have different scopes where we can run our coroutines, and I thought an app would crash if we try to update our UI while we're on the IO scope. Normally, on this scenario, this runtime exception would be shown:

android.util.AndroidRuntimeException: Animators may only be run on Looper threads

Weirdly enough, this doesn't happen on my app when I update the text of a textview. Here's an example of what I mean:

fun myFunction() {

   CoroutineScope(Dispatchers.IO).launch {
      textView.text = "Hello" // This should throw an exception, right? But it doesn't
      inputLayout.editText!!.text.clear() // This DOES throw an exception tho
   }

}

Could you help me understanding why does textView.text = "Hello" not throw an exception? Am I miss-understanding some basic coroutines concepts?

Thanks!

1 Answers

Dispatchers.IO --> is used to do the network and disk-related work.

Dispatchers.Main --> is used to do work on the UI thread of Android.

Default dispatcher ---> is used to do the CPU intensive work.

// Job and Dispatcher are combined into a CoroutineContext
private val job = SupervisorJob()
private val ioScope by lazy { CoroutineScope(job + Dispatchers.IO) }

fun myFunction() {
      ioScope.launch {
          withContext(Dispatchers.Main) {
              textView.text = "Hello"
              inputLayout.editText!!.text.clear(
           }
       }
 }

Reference doc : https://www.raywenderlich.com/34262147-kotlin-coroutines-tutorial-for-android-advanced

Related