Search code examples
multithreadingkotlinrunnable

Without AsyncTask, running a thread in background and updating the UI Thread


I was trying to update the recycler view content from a background thread in Kotlin. I am not using AsyncTask.

Here is my code, i want to know if there is any better way than this:

In my MainActivity, i have progressThread as a member variable.

 var progressThread = Thread()

Then in my method where i want to run the thread first i am defining it...like

        progressThread = Thread (
    Runnable {
        kotlin.run {
            try {
            while (i <= 100 && !progressThread.isInterrupted) {
                Thread.sleep(200)
                //Some Logic
                runOnUiThread {
                    //this runs in ui thread

                }
                i++
            }
            }catch (e:InterruptedException){
                progressThread.interrupt()
            }
        }
    })

after that i am starting it in the same method as

 progressThread.start()

and for stopping it, i have a listener to cancel the progress and in the callback of that listener, i have written:

 progressThread.interrupt()

Solution

  • Updated

    Coroutines are stable now,: https://kotlinlang.org/docs/reference/coroutines-overview.html


    Old Answer

    Yes, you can do this using doAsync from kotlin anko library that is fairly simple and easy to use.

    add following line in module level gradle file:

    compile "org.jetbrains.anko:anko-commons:0.10.0"
    

    Code example:

    val future = doAsync {
        // do your background thread task
        result = someTask()
    
        uiThread {
            // use result here if you want to update ui
            updateUI(result)
        }
    }
    

    code block written in uiThread will only be executed if your Activity or Fragment is in foreground mode (It is lifecycle aware). So if you are trying to stop thread because you don't want your ui code to execute when Activity is in background, then this is an ideal case for you.

    As you can check doAsync returns a Future object so you can cancel the background task, by cancel() function:

    future.cancel(true)
    

    pass true if you want to stop the thread even when it has started executing.

    If you have more specialised case to handle stopping case then you can do the same thing as in your example.

    You can use Kotlin Coroutines also but its in Experimental phase, still you can try it out: https://kotlinlang.org/docs/reference/coroutines.html