I have an api at http:/some.api
and a GET
endpoint data
which requires authentication through bearer token received through POST
auth
endpoint. The given security token is expired every 1 hour so I need to make a POST http:/some.api/auth
request in case I receive 401 on GET http:/some.api/data
, renew access token and make the same call to data
with the new access token without my client knowing anything about it. Current examples provide the Call
type which I can enqueue
(call) from the UI thread without it stopping, something analogous to .net
's async/await
feature. Now, if I were using .net
, I would wrap up the the whole logic and it would look like this:
async Task<DataModel> GetDataAsync()
{
try
{
return await GetDataInternalAsync();
}
catch(InvalidTokenException)
{
await ReAuthenticateAsync();
return await GetDataInternalAsync();
}
}
and call await GetDataAsync()
from the UI thread without worries. However, current examples only show how to make a call and handle results "on spot" from the calling method, for example:
Call<DataModel> call = apiService.getData();
call.enqueue(new Callback<DataModel>() {
@Override
public void onResponse(Call<DataModel> call, Response<DataModel> response) {
// todo deal with returned data. what if it is 401 and i need to make the same request after making the request to auth?
}
public void onFailure(Call<DataModel> call, Throwable t) {
// todo deal with the failed network request
}
});
What would be the way to organize calls architecture for my needs using Retrofit?