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>() { 
        @Override 
        public Boolean call() throws Exception { 
            return sharedPreferences.edit().clear().commit(); 
        } 
    }); 
}

Reference:

https://medium.com/yammer-engineering/converting-callback-async-calls-to-rxjava-ebc68bde5831

Please follow and like us:
Posted in: Android

Comments

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 :)