Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I call multiple requests at the same time in Retrofit 2

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
like image 851
Adem Avatar asked Mar 06 '16 12:03

Adem


People also ask

Can you use multiple Baseurl in retrofit?

Yes, you can create two different Service instances.

What is call in retrofit?

Think of Call as a simple class which wraps your API response and you need this class make an API call and provide listeners/callback to notify you with error and response , although if you use kotlin coroutines then after version 2.6.


1 Answers

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.)
like image 174
bkach Avatar answered Sep 21 '22 05:09

bkach