7

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

I can call them one by one of course, but is there any suggested method in retrofit ?

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
Adem
  • 9,402
  • 9
  • 43
  • 58

2 Answers2

10

I would take a look at using RxJava with Retrofit. I like the Zip function, but there's a ton of others. Here's an example of 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
);

Which results in

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

Retrofit shouldn't be much more difficult.

Your Retrofit service Objects should return an Observable<...> or Observable<Result<...>> if you want the status codes.

You'd then call:

Observable.zip(
    getMyRetrofitService().getCall1(),
    getMyRetrofitService().getCall2(),
    (result1, result2) -> return [result1,result2])
    .subscribe(combinedResults -> //Combined! Do something fancy here.)
bkach
  • 1,431
  • 1
  • 15
  • 24
  • if 1 request fails, will it stop the whole execution? @bkach? – ericn Jun 20 '17 at 08:29
  • With respect to HTTP status codes: With Retrofit 1, yes it will stop execution and throw an exception. With Retrofit 2 it does not. [Source (under request execution)](https://futurestud.io/tutorials/retrofit-2-upgrade-guide-from-1-9). Otherwise - on any other "failure" (crash, etc.) - yes it will stop execution and throw the exception. This can be handled in the `onError` which I have not implemented in the above example. – bkach Jun 20 '17 at 08:37
0

You can add both call in a collection and using parallelStream of Java8 to make the two calls in parallel

    Arrays.asList( myService.getCall1(), myService.getCall2()).parallelStream().map(call->call.request());
paul
  • 12,873
  • 23
  • 91
  • 153