aaronmarino
aaronmarino

Reputation: 4002

Sequential requests with retrofit

I'm using retrofit to connect to an API that includes a unique token in each response. This token must then be included in the next request. This means that I need to wait for a response to a request before making the next request.

Is there a built in mechanism in retrofit to achieve this? If not what would be the recommended approach? Note that I'm using asynchronous retrofit methods and version 1.9. Interceptors are being used to read the token and add it to the next request automatically, which works very well. The issue arises when 2 requests are made in close proximity, so the second request ends up using a stale token as the first request has not yet returned the new one.

Upvotes: 2

Views: 1105

Answers (1)

Christopher
Christopher

Reputation: 10279

I would suggest you to use RxAndroid in combination with Retrofit (Retrofit supports RxJava).

With this you can easily chain calls, like:

webservice.getToken()
    .flatMap(new Func1<Response, Observable<Response>>() {

           @Override
           public Observable<Response> call(Response getTokenResponse) {
              String token = ... // TODO extract token.
              return webservice.getDataFromWeb(token);
           }
        })

With webservice.getToken() you will retrieve the token. The Response of this call is passed as parameter getTokenResponse to the flatMap-operator. Here you can extract the token and you can perform a 2nd call with this token.

As this is a complex topic, some further reading may be necessary, I would suggest the following links for RxAndroid:

https://github.com/ReactiveX/RxAndroid

https://github.com/ReactiveX/rxjava/wiki

http://blog.danlew.net/2014/09/15/grokking-rxjava-part-1/

http://joluet.github.io/blog/2014/07/07/rxjava-retrofit/

Upvotes: 1

Related Questions