How can I call multiple requests at once in Retrofit 2

I have two different REST methods, and I want to call them at the same time. How to do it in Retrofit 2?

I can name them one by one, but is there any suggested method in the modification?

I expect something like:

Call<...> call1 = myService.getCall1(); Call<...> call2 = myService.getCall2(); MagicRetrofit.call (call1,call2,new Callback(...) {...} ); // and this calls them at the same time, but give me result with one method 
+6
source share
2 answers

I would look at using RxJava using Retrofit. I like the Zip feature, but there are a ton of others . Here is an example Zip using Java 8:

 odds = Observable.from([1, 3, 5, 7, 9]); evens = Observable.from([2, 4, 6]); Observable.zip(odds, evens, {o, e -> [o, e]}).subscribe( { println(it); }, // onNext { println("Error: " + it.getMessage()); }, // onError { println("Sequence complete"); } // onCompleted ); 

The result is

 [1, 2] [3, 4] [5, 6] Sequence complete 

Retrofitting should not be much more complicated.

Your update service. Objects must return Observable<...> or Observable<Result<...>> if you need status codes.

Then you called:

 Observable.zip( getMyRetrofitService().getCall1(), getMyRetrofitService().getCall2(), (result1, result2) -> return [result1,result2]) .subscribe(combinedResults -> //Combined! Do something fancy here.) 
+7
source

You can add both calls to the collection and use parallelStream Java8 to make two calls in parallel

  Arrays.asList( myService.getCall1(), myService.getCall2()).parallelStream().map(call->call.request()); 
0
source

All Articles