【发布时间】:2017-07-10 15:24:19
【问题描述】:
我是 RxJava 的新手。我有一个场景,我想调用第一个登录 Web 服务 (getLoginObservable),成功后,想调用另一个 Web 服务 (getFetchDataObservable) 来获取用户信息。
如果登录成功,我将运行以下代码。但我无法弄清楚如何编码failure 案例。
private void doLogin() {
emailAddress = editTextUsername.getText().toString();
final String password = editTextPassword.getText().toString();
showProgress(null, getString(R.string.loggingInPleaseWait));
getLoginObservable(editTextUsername.getText().toString(), password)
.map(response -> {
if (response.result) {
getPresenter().saveUserDetails(getContext(), emailAddress, true, response.dataObject.questionId, response.dataObject.question);
}
return response;
})
.flatMap(response -> {
return getFetchDataObservable();
})
.subscribe(res -> {
dismissProgress();
if (res.result) {
saveInformation(password, res);
} else {
ConstantsMethods.showOkButtonDialog(getContext(), res.message, null);
}
}, e -> {
dismissProgress();
if (e instanceof NoInternetConnectionException) {
ConstantsMethods.showOkButtonDialog(getContext(), getString(R.string.noInternetConnection), null);
}
Log.e(LoginFragment.class.getSimpleName(), e.getMessage());
});
}
private Observable<WsResponse<SecurityQuestion>> getLoginObservable(String userName, String password) {
return Observable.<WsResponse<SecurityQuestion>>create(subscriber -> {
getPresenter().doLogin(getActivity(), userName, password, appType,
new Callback<Void, WsResponse<SecurityQuestion>>() {
@Override
public Void callback(final WsResponse<SecurityQuestion> param) {
subscriber.onNext(param);
return null;
}
});
});
}
private Observable<WsResponse<PatientDataProfile>> getFetchDataObservable() {
return Observable.create(subscriber -> {
new AfPatientsPresenter().fetchPatientData(getContext(), emailAddress, "", new Callback<Void, WsResponse<PatientDataProfile>>() {
@Override
public Void callback(WsResponse<PatientDataProfile> param1) {
subscriber.onNext(param1);
subscriber.onComplete();
return null;
}
});
});
}
就我对 RxJava 的了解而言,我可以发现 getLoginObservable(editTextUsername.getText().toString(), password) observable 向 map (map(response -> { ... }) 发送响应,而此 map 返回对 flatmap (flatMap(response -> { ... }) 的响应,并将其响应发送给订阅者。在这里,我迷失了如何跳过(第二次网络调用)平面图flatMap(response -> { ... },以在登录失败的情况下直接向订阅者发送响应。
【问题讨论】:
标签: android rx-java rx-android