1

So, I am aware of the fact that in Android, views cannot be updated from a background thread. I have a TextView called appTitle. I am launching a coroutine on background thread ( IO ) and on that background thread, I am updating the title of TextView.

Technically that code should fail. But it is not raising any exceptions and is working fine. I am curious as to why this thing is not raising any exceptions like : CalledFromWrongThreadException

P.S TO make the matter even worse, I am constantly updating the title every half second, not to miss any special case that would otherwise arise due to how render cycles work.

CoroutineScope(Dispatchers.IO).launch{
            Log.d(TAG, "onCreate Current thread name: ${Thread.currentThread().name}")
            val arr = arrayOf(appTitle.text.toString(),"Modified App Title")
            var index = 0;
            for (i in 1..100){
                appTitle.text =arr[index]
                delay(500)
                if(index==0)index=1
                else index =0
             }
        }
    
3
  • Wrap any UI update inside withContext(Dispatchers.Main) to guarantee main thread execution: CoroutineScope(Dispatchers.IO).launch { ...... withContext(Dispatchers.Main) { appTitle.text = arr[index] } ...... } } Commented Jul 7 at 8:29
  • What object is appTitle ? Commented Jul 7 at 11:22
  • @Thommy its a TextView Commented Jul 7 at 11:26

1 Answer 1

0

I tried this on my app and it worked there as well. This behavior doesn't break the specification, though: you are not guaranteed to get an exception. There are some best-effort mechanisms in place to help you write the UI code properly.

You are certainly not guaranteed to not get an exception, either, or that this background thread access to UI will work in all circumstances and on all devices. Sometimes a non-synchronized memory operation will propagate to the UI thread, and sometimes it won't or it will but at an unexpected time or out of order with other operations from the same background thread.

So, don't take this experiment as proof that your code is correct.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.