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
Yes, you can create two different Service instances.
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.
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.)
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