We are using RxJava in Android a lot, with good reasons. However, we still need to use code that is not built with RxJava, so let’s wrap them.
For very simple synchronous APIs, you can use Observable.just() to wrap them. e.g. you can use Observable.just(1, 2, 3, 4, 5) to emit an integer sequence from 1 to 5.
If the API is blocking, you can use Observable.defer() to wrap them:
And if you want RxJava to do try...catch for you, you can use Observable.fromCallable():
Usually, existing code uses callbacks to support asynchronous operations, e.g. in Android we can request location updates like this:
For advanced RxJava users, who don’t need to read this article, you can use Observable.create() to wrap it, and fullfil the contract by yourself. But for us, we can easily use Observable.fromEmitter() to handle the case, and let the framework to help us: