Making APIs Reactive with RxKotlin
Convert any callback/async calls using RxKotlin

Who's this article for?
- You have some knowledge about RxJava2 or RxKotlin
- You want to convert callback-style APIs into reactive
The problem
When working with ReactiveX in a project, it's important to keep consistency of the reactive paradigm throughout the whole project. With the growing popularity of Rx in Android projects (i.e Rxjava & RxKotlin), it's likely that you'll find APIs that already provide a reactive model (e.g Retrofit, Google Room). In case there's no reactive model, with RxKotlin, you can convert practically any API to Rx.
Use case: Retrieving places nearby
For the sake of this article, we will consider the use case of retrieving the user's current location and then fetching the places nearby using Google places API
First of all, let's assume that we already have a reactive way of retrieving places nearby as the following
The API for getting this list is the following
https://maps.googleapis.com/maps/api/place/nearbysearch/json? location=$latitude, $longitude
Next, in order to retrieve the user's current location we need the following function:
In this case, the fusedClient.lastLocation receives two callbacks (onSuccess & onFailure) and then inside those callbacks, you can retrieve the user's location. How can we combine both functions in a reactive way?
Wrapping the location API into Rx using Single.create()
According to the ReactiveX documentation for Flowable.create:
Provides an API (via a cold Flowable) that bridges the reactive world with the callback-style, generally non-backpressured world.
This is exactly what we need to use in order to convert callback-style APIs into reactive ones. So, we wrap the content of the function getLocation() like this:
Great! Now we can combine this function with getNearbyPlaces()
Combining streams together
Since we are using reactive models for both features we can finally combine them ending up with this beautiful 2 lines of code!
