Eselfar
Eselfar

Reputation: 3869

RxJava 2 & Retrofit 2 sequential independent calls

I'm calling an API. When the app starts I need to get a token from the API to be able to do the other calls. The token is managed by a "token manager" inside the app. I'm using RxJava 2 and Retrofit 2 to manage the call.

When I launch the app, the Token Manager get the token and the Fragment gets the data. I expected the calls to be executed sequentially as both are using the same Retrofit client object injected with Dagger 2. But, in fact, the call to get data is executed before the call to get the token finishes, and as this call needs the token, the request fails.

Some people suggest to use a flatmap but I can't as the logic are managed at two different places in the app (the TokenManager class and the Fragment). How can I solve my issue?

Upvotes: 0

Views: 898

Answers (1)

Mohamed Ibrahim
Mohamed Ibrahim

Reputation: 3924

So from your description you mentioned that you can't use flatmap(), but according to your requirements it seems that one of the two calls is dependent on the other.

anyway the possibilities are as follow:

Dependent calls - same place (e.g Activity)
in that case you should use flatMap() for example calls A and B, call A must get token so B could be executed.
Dependent calls - different places (e.g Service - Activity)
the most fit way for this situation is an event bus, and you can use PublishSubject from Rxjava to implement such an event bus.

so in your case the second solution is the way to go. you get the Token in your TokenManger, then notify any screen need it, you could notify its expiration too, so app doesn't hit the network unnecessarily.

as a simple example:

PublishSubject<Token> publishToken = PublishSubject.create();

//notify others that you got a Token
publishToken.onNext(myToken);
..
..
//in other place (eg fragment)
getTokenEventBus().subscribe(token -> {
  //do your other call
 }, throwable ->{ 
  //handle error
 }, () -> {
  //event complete
});

Upvotes: 1

Related Questions