我有两种不同的REST方法,我想同时调用它们。我怎样才能在Retrofit 2中做到这一点?
我当然可以逐个打电话给他们,但是在改造中是否有任何建议的方法?
我期待的是:
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
答案 0 :(得分:8)
我会看一下使用RxJava和Retrofit。我喜欢Zip函数but there's a ton of others。以下是使用Java 8的Zip示例:
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
);
结果是
[1, 2]
[3, 4]
[5, 6]
Sequence complete
改造不应该困难得多。
您的改造服务如果您想要状态代码,对象应返回Observable<...>
或Observable<Result<...>>
。
然后你打电话:
Observable.zip(
getMyRetrofitService().getCall1(),
getMyRetrofitService().getCall2(),
(result1, result2) -> return [result1,result2])
.subscribe(combinedResults -> //Combined! Do something fancy here.)
答案 1 :(得分:0)
您可以在集合中添加两个调用并使用Java8的parallelStream来并行执行两个调用
<?php namespace App\Providers;
use App\Chat;
use Auth;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider {
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot() {
if (Auth::check()) {
$total_mess = Chat::whereRaw('view = ? and to_user = ?', [0, Auth::user()->username])->count();
view()->share('total_mess', $total_mess);
}
if (Auth::guest()) {
view()->share('total_mess', '');
}
}