2017-03-22 4 views
1

私はある種類のResultをサーバから取得しています。私は、観察可能なシーケンスを構築しようとしています: 1.結果が成功したことを確認します(result.success()) 2.そうであれば、結果から文字列リソースを取得します(result.getResource())その文字列で観測可能なものを返します。 3.エラーがなければ、エラー処理コードを実行して空の観測を返します。RxJava2は分岐ロジックのために結果を失う

簡単なswitchMapで簡単に実現できますが、できる限り別々の操作を分けておきたいので、私は好きではありません。理想的には、別のコンシューマで障害処理をしたいのですが、問題はResultオブジェクトを失うことなく.success()メソッドの結果を渡すことができないことです。私が必要とするものを達成する方法はありますか?

は今、私のコードは次のようなものになります。あなたはそれに格納された結果でカスタムExceptionを作ることができます

Observable<String> getResource() { 
      return getServerResult() 
      .switchMap(new Function<Result, ObservableSource<String>>() { 
       @Override 
       public ObservableSource<String> apply(Result result) throws Exception { 
        if (result.success()) { 
         return Observable.just(result.getResource()); 
        } else { 
         onFailure(result); // not happy about this side effect being here 
         return Observable.empty(); 
        } 
       } 
      }); 

答えて

2

を、ストリームエラーにそれをラップしている場合flatMapでそれを返す成功しないで、結果doOnErrorを使用してコール副作用を行い、ErrorResumeNextObservableに戻します。

class MyCustomException extends Exception { 
    Result result; 
} 

//do you really need switchMap? 
.flatMap(result -> { 
    if (result.success()) { 
     return Observable.just(result.getResource()); 
    } else { 
     return Observable.error(MyCustomException(result)); 
    } 
}) 
//do* operators is meant to call side effect methods without changing the stream 
.doOnError(exception -> { 
    if(exception instanceof MyCustomException) { 
     Result result = ((MyCustomException) exception).getResult(); 
     onFailure(result); 
    } 
}) 
.onErrorResumeNext(exception -> { 
    if(exception instanceof MyCustomException) { 
     return Observable.empty(); 
    } else { 
     return Observable.error(exception); //propagate error downstream 
    } 
}) 
関連する問題