2017-06-24 6 views
1

基本的に私は最初にユーザーにログインしなければなりません。もしsucessfullなら、ショップとログアウトを追加する必要があります。Retrofit、RxJavaが最初に成功した場合にリクエストをします

Observable<BaseResponse<String>> loginObs = apiService.Login(merchant); 
Observable<BaseResponse<Merchant>> addShopObs = apiService.addShop(shop); 
Observable<BaseResponse<String>> logoutObs = apiService.Logout(); 

ベースの応答は、ログインが成功した場合、私は決めるべきベースの成功のフィールドを持って与えられるように改造インタフェースは、観測が作成された

@POST("merchant/register") 
Observable<BaseResponse<String>> Login(@Body Merchant merchant); 

@PUT("merchant/{username}") 
Observable<BaseResponse<Merchant>> Logout(); 

@POST("shop") 
Observable<BaseResponse<Shop>> addShop(@Body Shop shop); 

以下の通りです。私は最初のログインオブザーバーの成功を確認するためにマップを使用することができると思うが、ログインが失敗した場合に何をすべきか分からない。どうすればチェーン全体をキャンセルできますか?

答えて

3

あなたは、ログインの成功に応じて、別の観測可能に、loginObsとflatMap loginResponseを始めるので、addShopObsを返すか

観察可能なエラーを返すのいずれかのことができます(つまり、エラーでチェーンを終了します)

次に、通常通り、merchantResponseをlogoutObsにflatMapすることができます。ここで

は、それを達成することができる方法は次のとおりです。

loginObs(merchant) 
    .flatMap(loginResponse -> { 
     if (/*successful check*/) 
      return addShopObs; 
     else 
      return Observable.error(new Exception("Login failed!")); 
      // or throw your own exception, this will terminate the chain and call onError on the subscriber. 
    }) 
    .flatMap(merchantResponse -> logoutObs) 
    .subscribe(logoutResponse -> { 
     /*all operations were successfull*/ 
    }, throwable -> { 
     /*an error occurred and the chain is terminated.*/ 
    }); 
関連する問題