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:
- Make a API1 request to create media ID.
- Get the media upload URL from location header of API1.
- Upload file to that media upload URL.
- Store the media ID to the media.
- Wait for push notification with media ID to confirm that the job on server side for that media is done.
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:
RxJava.flapMap() to chain the API1 -> API2:
And its subscriber:
And its new subscriber can get the pair of media ID and
We also can use
cache() to help alternatively.
The operator order is
There are still some variants for this use case, you can find it out by yourself, happy coding!