Posted by on 14th January 2019

Converting callback async calls to RxJava

APIs usually offer one of these two options when dealing with expensive operations:

  1. synchronous blocking method call (expected to be called from a background thread)
  2. An asynchronous non-blocking method call that uses callbacks (and/or listeners, broadcast receivers, etc)

Converting synchronous APIs to Observables

For the first type of APIs, RxJava offers a convenient factory method named Observable.fromCallable(). For example, this is how it would look to convert the commit method from Android’s SharedPreferences API:

// wrapping synchronous operation in an RxJava Observable
Observable<Boolean> wipeContents(final SharedPreferences sharedPreferences) { 
    return Observable.fromCallable(new Callable<Boolean>() { 
        public Boolean call() throws Exception { 
            return sharedPreferences.edit().clear().commit(); 


Please follow and like us:
Posted in: Android


Be the first to comment.

Leave a Reply

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>


Enjoy this blog? Please spread the word :)