1

我有一个flatMap运行一系列 HTTP 调用来注册用户、检索他们的个人资料和其他一些事情的方法。我想根据错误发生的阶段通知onErrorsubscription特定的错误消息。flatMap也许注册成功,但检索创建的配置文件却没有。我怎样才能做到这一点,以便flatMap在发生错误时停止所有后续调用?

这是我的一些伪代码Observableand Subscription

Retrofit.registerUser()
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .flatMap({
            return Retrofit.authenticate();
        })
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .flatMap({
            return Retrofit.retrieveProfile() 
        })
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .flatMap({
            return Retrofit.retrieveOtherStuff()
        })
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new Action1 {

        }, new Action1<Throwable>() {
          // I would like to display the error to my user here
        }));
4

1 回答 1

1

至少有两种方法可以做到:

  1. 使用doOnError运算符:

    Retrofit.registerUser()
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .doOnError(error -> {
            showRegistrationFailedError(error);
        })
        .flatMap({
            return Retrofit.authenticate().doOnError(error -> {
                showAuthenticationFailedError(error);
            });
        })
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new Action1 {
    
        }, new Action1<Throwable>() {
          // do nothing here. all errors are already handled in doOnError methods
        }));
    
  2. 使用onErrorResumeNext运算符:

    Retrofit.registerUser()
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .onErrorResumeNext(error -> {
            return Observable.error(new RegistrationFailedException(error));
        })
        .flatMap({
            return Retrofit.authenticate().onErrorResumeNext(error -> {
                return Observable.error(new AuthenticationFailedException(error))
            });
        })
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(value -> {
    
        }, error -> {
            if (error instanceof RegistrationFailedException) {
                showRegistrationFailedError(error);
            }
    
            if (error instanceof AuthenticationFailedException) {
                showAuthenticationFailedError(error);   
            }
        }));
    
于 2015-07-15T22:02:16.923 回答