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

与世无争的帅哥 提交于 2021-02-07 13:15:58

问题


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

回答1:


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.)



回答2:


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());


来源:https://stackoverflow.com/questions/35827090/how-can-i-call-multiple-requests-at-the-same-time-in-retrofit-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!