连锁改造如何调用?
如何进行一次又一次的改造?
How can I make one retrofit 2 call after another?
我正在阅读有关 RxJava 的文章,并且我已经在使用 RxJava 进行调用,但是我还没有找到如何使用 flatMaps 的好例子.
I'm reading about RxJava and I'm already doing my calls using RxJava, but I havn't found a good exemple of how to use flatMaps.
有人可以向我解释如何做吗?
Can someone explain how to do it to me?
我正在尝试拨打这两个电话,在这两个电话都完成后,我想开始一项新活动.
I'm trying to make these two calls, and after they're both done, I want to start a new activity.
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Retrofit retrofit = new Retrofit.Builder()
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.baseUrl("http://api.openweathermap.org/data/2.5/")
.build();
WeatherService weatherService = retrofit.create(WeatherService.class);
final Observable<Weather> london = weatherService.getCurrent();
london.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Subscriber<Weather>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
}
@Override
public void onNext(Weather weather) {
Log.i("WEATHER","Weather Name: " + weather.getName());
}
});
final Observable<Wind> windObservable = weatherService.getWind();
windObservable.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Subscriber<Wind>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
}
@Override
public void onNext(Wind wind) {
Log.i("WEATHER","Wind: " + wind.getSpeed().toString());
}
});
}
}
也许这个链接:https://github.com/ReactiveX/RxJava/wiki/Combining-observables 会有所帮助.结帐 zip.最终 switchMap 方法可能对您有用.
Maybe this link: https://github.com/ReactiveX/RxJava/wiki/Combining-observables will help. Checkout for zip. Eventually switchMap method may be useful in Your case.
也许这个例子 http://joluet.github.io/blog/2014/07/07/rxjava-retrofit/ 会帮助你更多.
Maybe this example http://joluet.github.io/blog/2014/07/07/rxjava-retrofit/ will help You even more.
编辑 #2:一些代码
login().switchMap(new Func1<FirstResponse, Observable<SecondResponse>>() {
@Override
public Observable<SecondResponse> call(FirstResponse t) {
if (ApiUtils.isLoginValid(t)) {
return profile(t.getToken());
}
else{
return Observable.error(new CustomException());
}
}
}
}).subscribe(subscriber());
注意:profile方法返回类型是Observable
,订阅者方法类型是Subscriber
Note: profile method return type is is Observable<SecondResponse>
and subscriber method type is Subscriber<? super SecondResponse>