runOnUiThread is not calling

Ankur Khandelwal picture Ankur Khandelwal · Apr 25, 2017 · Viewed 24.9k times · Source
localChatManager.addIncomingListener { from, message, chat ->

                Log.v(TAG,"listener")


                //You can't modify views from non-UI thread.
                [email protected] { object :Runnable{
                    override fun run() {
                        Log.i(TAG,"runOnUiThread")
                     }
                } }
            }

I am not able to figure out why runOnUiThread is not working but outside of that method everything is working as usual.

Answer

zsmb13 picture zsmb13 · Apr 25, 2017

What you are doing is passing in a lambda to the runOnUiThread function. It will run that lambda, and create an object that inherits from Runnable, and then do nothing with it. Maybe you can see that a little bit better if you format it like this (added some extra log statements and explanation):

runOnUiThread({
    Log.i(TAG, "This is run")
    object : Runnable {                    // This whole expression
        override fun run() {               // returns an object which
            Log.i(TAG, "runOnUiThread")    // is a Runnable, but does
        }                                  // not at any point invoke
    }                                      // its "run" method
    Log.i(TAG, "And so is this")
})

The created object is not assigned to a variable, and is never used. If you want to pass in a Runnable instance to the runOnUiThread method, you can do that by just putting it inside the parentheses of the runOnUiThread call:

runOnUiThread(
        object : Runnable {
            override fun run() {
                Log.i(TAG, "runOnUiThread")
            }
        }
)

The simplest way to use runOnUiThread though is to pass in a lambda to it using SAM conversion, and writing the code you want to execute directly inside that.

runOnUiThread { 
    Log.i(TAG, "runOnUiThread") 
}

Here's the official documentation covering SAM conversions, which happens to use Runnable in its examples.