I make a request (any, authorization, registration, etc.) and only then I find out that I need to update TOKEN , that is, I get an error 401 .

Here is a request for authorization:

 BaseApplication.getApiClient() .signIn(accessToken, body) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new SingleObserver<UserProfile>() { @Override public void onSubscribe(Disposable d) { Log.d("-- SignInOnSubscribe", "Subscribed!"); } @Override public void onSuccess(UserProfile userProfile) { if (userProfile.getErrorDetails() != null) { onSignInFinishedCallback.onLoginFailure(userProfile.getErrorDetails()); Log.d("-- SignInOnError", userProfile.getErrorDetails()); } else { onSignInFinishedCallback.onLoginSuccess(userProfile); profileRepository.updateUserProfile(userProfile); Log.d("-- SignInOnSuccess", userProfile.getName()); } } @Override public void onError(Throwable e) { Log.d("-- SignInOnError", e.getMessage()); if (e.getMessage().equals(Constants.CODE_UNAUTHORIZED)){ // Действие при ошибке 401 } onSignInFinishedCallback.onLoginFailure(e.getMessage()); } }); 

API requests themselves:

 @POST("/api/login") Single<UserProfile> getAccessToken(@Body Map<String, String> requestBody); @POST("/api/abonent/login") Single<UserProfile> signIn(@Header("X-ACCESS-TOKEN") String accessToken, @Body Map<String, String> requestBody); 

Let's say an authorization запрос 1 is запрос 1 , a TOKEN запрос 2 is запрос 2 .

Question: How to update TOKEN if I received an error in запросе 1 and after the success of запроса 2 , back to запрос 1 ?

    1 answer 1

    The task of refreshing a token can be solved using OkHttp Interceptors.

    What is the Interceptor ? This is the class that intercepts all your requests executed through the specified OkHttClient .

    It should be connected to the client, example:

     OkHttpClient client = new OkHttpClient.Builder() .addInterceptor(new TokenRefresherInterceptor()) .build(); 

    What to do in interceptor?

     class TokenRefresherInterceptor implements Interceptor { @Override public Response intercept(Interceptor.Chain chain) throws IOException { Request request = chain.request(); // получили запрос который вы отправили на сервер. Response response = chain.proceed(request); //тут выполняется запрос и результат в response. //далее вы работаете с этим response. //Проверяете, какой ответ вам пришел. //Если в нём лежит 401. значит вы формируете запрос на обновление токена, //выполняете его в этом же интерсепторе дальше. и снова проверяете результат. //если токен рефрешнулся то повторяете изначальный запрос return response; } } 

    There are many more articles on this topic in Google)