TL;DR: I want to execute multiple Call
s (Retrofit) like you can .zip()
multiple Observable
s (RxJava2).
I have a retrofit2 function:
@GET("/data/price")
Call<JsonObject> getBookTitle(@Query("id") String id, @Query("lang") String lang);
I can execute it (async) in code with enquene()
:
ApiProvider.getBooksAPI().getBookTitle(bookId, "en").enqueue(new Callback<JsonObject>() {
@Override
public void onResponse(Call<JsonObject> call, Response<JsonObject> response) { }
@Override
public void onFailure(Call<JsonObject> call, Throwable t) { }
});
Now I want to execute multiple Call
s at once (get multiple book titles) and be notified when all requests are done. Here is when I am missing knowledge.
I know I could start using Observable
(RXJava2) instead of Call
(Retrofit2):
@GET("/data/price")
Observable<JsonObject> getBookTitle(@Query("id") String id, @Query("lang") String lang);
and then merge calls like in below example. But this code seems much more complex and long (especially if I only need 1 book title). Isn't there any way I could merge Call
s without using Observable
?
List<Observable<JsonObject>> mergedCalls = new ArrayList<>();
mergedCalls.add(ApiProvider.getBooksAPI().getBookTitle(bookId1, "en"));
mergedCalls.add(ApiProvider.getBooksAPI().getBookTitle(bookId2, "en"));
mergedCalls.add(ApiProvider.getBooksAPI().getBookTitle(bookId3, "en"));
Observable<List<JsonObject>> observable = Observable.zip(calls, responses -> {
// merge responses, return List
...
})
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io());
observer = new DisposableObserver<List<JsonObject>> () {
@Override
public void onNext(List<JsonObject> result) { // got all API results }
@Override
public void onError(Throwable e) { }
@Override
public void onComplete() { }
};
observable.subscribe(observer);
Observable
. Is there any shorther way (compared to my last code above) to get just 1 book title? WithCall
there are no extra objects, but withObservable
I need to makeObservable
,Observer
and take care to properly dispose everything etc, which makes code very ugly as opposed toCall
. – Ultimogeniture