2

I'm new in rxjava or rxandroid, and looking for a better way dealing with multiple requests. I need to get the token from server and use the result as a parameter to do login verification and if it returns success then get the sessionId through getSessionId method. I've considered about zip or merge, but I don't think it'll work. So can you give me an idea or I don know , train of thought? Thank you.

Here's my code:

private void getToken(final String name , final String pwd){
    api.newToken()
    .subscribeOn(Schedulers.newThread())
    .observeOn(AndroidSchedulers.mainThread())
    .subscribe(new Action1<TokenModel>() {
      @Override public void call(TokenModel tokenModel) {
        String token = tokenModel.request_token;
        if (!"".equals(token)){
          login(token, name, pwd);
        }else {
          Timber.e("got token failed");
        }
      }
    });
  }

private void login(String token, String name, String pwd){
    api.validateToken(token, name, pwd)
    .subscribeOn(Schedulers.newThread())
    .observeOn(AndroidSchedulers.mainThread())
    .subscribe(new Action1<TokenModel>() {
      @Override public void call(TokenModel tokenModel) {
        String token = tokenModel.request_token;
        if (!"".equals(token)){
          getSessionId(token);
        }else {
          Timber.e("got token failed");
        }
      }
    });
  }

private void getSessionId(String token){
    api.newSessionn(token)
    .subscribeOn(Schedulers.newThread())
    .observeOn(AndroidSchedulers.mainThread())
    .subscribe(new Observer<TokenModel>() {
      @Override public void onCompleted() {
        //go to home activity
      }

      @Override public void onError(Throwable e) {
        //handle error
      }

      @Override public void onNext(TokenModel tokenModel) {
        //store session id
      }
    });
  }

1 Answer 1

3

Your first subscription call your second subscription, ...
You can avoid this using flapmap operator.

api.newToken(...)
     .flapMap(token -> api.validateToken(token))
     .flapMap(token -> api.newSession(token)).subscribe()

New observable in a subscription can offen be replaced by a flatMap call.

If you want to manage your error, in a flatMap, if the token is invalid, your can return an error observable instead of returning new api call observable.

.flatMap(token -> if(token.isValid){ return api.newCall(); } else { return Observable.error(...); ;)
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you , it helps a lot. By the way, can I handle the errors all in Observer? you know, the onError().
It depends but you can

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.