Basically I have to first login the user, if its successful them I have to add a shop and logout. The retrofit interface is given below
@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);
The observables are created as given
Observable<BaseResponse<String>> loginObs = apiService.Login(merchant);
Observable<BaseResponse<Merchant>> addShopObs = apiService.addShop(shop);
Observable<BaseResponse<String>> logoutObs = apiService.Logout();
The Base response has a success field based which i should decide if the login was successful. I think i can use map to verify the success of first login observer, but i don't know what to do if the login fails. How can i cancel the whole chain?
You can begin with the loginObs, flatMap the loginResponse to another observable depending on the success of the login, so either return the addShopObs or return an error observable
(that will terminate the chain with an error)
Then you can continue normally to flatMap the merchantResponse to the logoutObs.
Here's how it can be achieved:
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.*/
});