Ali Zarei
Ali Zarei

Reputation: 3753

Kotlin coroutines exception handler on main thread

I have a coroutine with an exception handler to call an API. I want to update UI if there is any exception but i got bellow error:

Caused by: android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.

So is there any way to update UI in exception handler?

Here is my code :

val exceptionHandler = CoroutineExceptionHandler { coroutineContext, exception ->

            binding.textview.text = exception.message

        }
        myJob = CoroutineScope(Dispatchers.IO).launch(exceptionHandler) {

            val result = webServices.getTest()

            withContext(Dispatchers.Main) {
                binding.textview.text = "$result"
            }
        }

Upvotes: 2

Views: 2628

Answers (1)

ChristianB
ChristianB

Reputation: 2690

I think there is no way that ensures CoroutineExceptionHandler is called on Main thread. Because you can be on any thread at any time where the crash can happen.

Documentation

From CoroutineExceptionHandler

CoroutineExceptionHandler can be invoked from an arbitrary thread.

See also this Issue on GitHub

Workaround

You could launch a coroutine on main dispatcher, as Roman Elizarov mentioned, in your CoroutineExceptionHandler:

GlobalScope.launch(Dispatchers.Main) { ... /* put code here */ ...  }

or if you have a lifecycleScope (because GlobalScope is not recommended):

lifecycleScope.launch(Dispatchers.Main) { ... /* put code here */ ...  }

Upvotes: 3

Related Questions