androidmultithreadingkotlinkotlin-coroutinesandroid-runonuithread

is there any difference between runOnUiThread and CoroutineScope(Dispatchers.Main) in Kotlin Android


I don't know is there any difference between CoroutineScope(Dispatchers.Main).launch and runOnUiThread, I think both will run on Main thread.

but still confusion is any difference there.?

Thanks.


Solution

  • Firstly, you can call runOnUiThread only in the context of Activity.

    Secondly, you cannot call suspend functions from runOnUiThread, while you can do it in CoroutineScope(Dispatchers.Main).launch block.

    Thirdly, runOnUiThread checks if the current ui thread is busy with other operations, if it is, the task is posted to an activity handler and will be executed when its turn will come.