RxJava: chain API1 -> API2 call and get API1 result

How can we chain the APIs and get result from one of the APIs?

Today let’s talk about a scenario: we’d like to implement a new feature to publish a new post on our app, and we have to follow the flow:

Technical Flow

  1. Make a API1 request to create media ID.
  2. Get the media upload URL from location header of API1.
  3. Upload file to that media upload URL.
  4. Store the media ID to the media.
  5. Wait for push notification with media ID to confirm that the job on server side for that media is done.
Media Upload.png
Flow Chat

 

API Request/Response

The first API to create media ID and get media upload URL:

The second API to upload media:

Problem to solve?

You need to call two APIs (or more) sequentially and chain together, both the two APIs success, then the publish flow successes, once one of the APIs fail, then the whole flow is considered to be failed.  After the both API calls, we have to get the post ID from API1, how can we chain the APIs and get result from the first API?

Here we use RxJava to help us solve this problem, and use Retrofit and Okhttp for API call, let’s convert each API requests into several standalone Observable: (for clear and convenient, we choose API1, API2, … to represent the first, second… API than the real production name)

1. We define the data class for API response first, this data class to store the response from API1:

2. The two APIs observables:

3. Use RxJava.flapMap() to chain the API1 -> API2:

flatMap.c.png
Source: http://reactivex.io/documentation/operators/flatmap.html

And its subscriber:

And its new subscriber can get the pair of media ID and okhttp3.Response:

Solution2

We also can use cache() to help alternatively.

replay.c.png
Source: http://reactivex.io/documentation/operators/replay.html

The operator order is api1.cache.flatmap(api2.zip(api1))

There are still some variants for this use case, you can find it out by yourself, happy coding!

 

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Blog at WordPress.com.

Up ↑