My API Client
public class ApiClient {
public static final String BASE_URL = "http://baseurl.com/wp-json/";
private static Retrofit retrofit = null;
public static Retrofit getClient() {
if (retrofit==null) {
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
My endpoint interface
public interface ApiInterface {
@GET("posts/category/politics/recent-stories/")
Observable<ArrayList<ModelNewsPaged>> getPoliticsArrayListObservable(@Query("per_page") int perPage, @Query("page") int page);
@GET("posts/category/economy/recent-stories/")
Observable<ArrayList<ModelNewsPaged>> getEconomyArrayListObservable(@Query("per_page") int perPage, @Query("page") int page);
@GET("posts/category/sports/recent-stories/")
Observable<ArrayList<ModelNewsPaged>> getSportsArrayListObservable(@Query("per_page") int perPage, @Query("page") int page);
}
How to make the web service call sequentially to getPoliticsArrayListObservable first and then getEconomyArrayListObservable and getSportsArrayListObservable using flatMap & without using lambda function?
I tried something like this:
final ApiInterface apiInterface = ApiClient.getClient().create(ApiInterface.class);
Observable.just(apiInterface)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.flatMap(new Function<ApiInterface, Observable<ArrayList<ModelNewsPaged>>>() {
@Override
public Observable<ArrayList<ModelNewsPaged>> apply(ApiInterface apiInterface) throws Exception {
return apiInterface.getPoliticsArrayListObservable(10,1);
}
})
.subscribe(new Observer<ArrayList<ModelNewsPaged>>() {
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onComplete() {
Log.d("flatMap", "onComplete");
}
@Override
public void onError(Throwable e) {
e.printStackTrace();
Log.d("flatMap", "onError");
}
@Override
public void onNext(ArrayList<ModelNewsPaged> integer) {
Log.d("flatMap", "Final result: " + integer.toString());
}
});
But the problem here is, I'm unable to chain any more flatMap methods. Any help will be much appreciated.
You can use Concat operator of RxJava to make the API call sequentially. If you don't care about the sequence you can use Zip.
Well, I might have done it something like this. The API calls should be treated as Single if you are not keeping an open connection with them.
apiService.getDailyCounts()
.flatMap { apiService.updateCounts() }
.flatMap { apiService.changeTrialCourtCaseName() }
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With