androidrx-javarx-java2android-handler

Replace Handler.post with RxJava


This might be an easy answer but since I am new to RxJava, so not quite sure.

I have a Handler for queuing Runnable. I want to perform certain tasks on main/UI thread for which currently I have below code:

private val handler = Handler(Looper.getMainLooper())
handler.post {
  //action on UI thread
}

//onDestroy()
handler.removeCallbacksAndMessages(null)

I want to perform the above tasks using RxJava. Please help.


Solution

  • If you want the equivilent in RxJava then Completable::fromRunnable is what you want :

        private val disposable = CompositeDisposable() // instance variable
        
        // Usage
        Completable.fromRunnable { 
                // Runnable action (should be side effect free)
        }.subscribeOn(AndroidSchedulers.mainThread())
            .subscribe(
                 { Log.i(TAG, "runnable completed")}, 
                 {t -> Log.e(TAG, "error", t)})
            .let(disposable::add)
    
       // onDestroy
       disposable.clear()
    

    I have indicated that the Runnable should be side effect free, the subscriber should perform any side effects (in this example simply logging). If that is not the case and you have side effects in your runnable then RxJava might not be the best fit for your use case.