@@ -12,21 +12,14 @@ class TokenInterceptor implements InterceptorsWrapper {
1212 static const _tokenUnavailableMessage =
1313 'Authentication token is unavailable for a protected request' ;
1414
15+ static bool _isRefreshing = false ;
16+ static final _requestsNeedRetry = < _RequestNeedingRetry > [];
17+
1518 final Dio dio;
1619 TokenInterceptor (this .dio);
1720 final TokenLocalDataSource tokenLocalDataSource = getIt
1821 .get <TokenLocalDataSource >();
1922
20- // when accessToken is expired & having multiple requests call
21- // this variable to lock others request to make sure only trigger call refresh token 01 times
22- // to prevent duplicate refresh call
23- bool _isRefreshing = false ;
24-
25- // when having multiple requests call at the same time, you need to store them in a list
26- // then loop this list to retry every request later, after call refresh token success
27- final _requestsNeedRetry =
28- < ({RequestOptions options, ErrorInterceptorHandler handler})> [];
29-
3023 @override
3124 void onRequest (
3225 RequestOptions options,
@@ -58,7 +51,13 @@ class TokenInterceptor implements InterceptorsWrapper {
5851 if (_shouldRefreshToken (err)) {
5952 final response = err.response;
6053 // if hasn't not refreshing yet, let's start it
61- _requestsNeedRetry.add ((options: err.requestOptions, handler: handler));
54+ _requestsNeedRetry.add (
55+ _RequestNeedingRetry (
56+ dio: dio,
57+ options: err.requestOptions,
58+ handler: handler,
59+ ),
60+ );
6261
6362 if (! _isRefreshing) {
6463 _isRefreshing = true ;
@@ -163,16 +162,14 @@ class TokenInterceptor implements InterceptorsWrapper {
163162 }
164163 }
165164
166- Future <void > _retryRequests (
167- List <({RequestOptions options, ErrorInterceptorHandler handler})> requests,
168- ) async {
165+ Future <void > _retryRequests (List <_RequestNeedingRetry > requests) async {
169166 await Future .wait (
170167 requests.map ((requestNeedRetry) async {
171168 final options = requestNeedRetry.options;
172169 options.extra[_retryAfterRefreshKey] = true ;
173170
174171 try {
175- final response = await dio.fetch (options);
172+ final response = await requestNeedRetry. dio.fetch (options);
176173 requestNeedRetry.handler.resolve (response);
177174 } on DioException catch (error) {
178175 requestNeedRetry.handler.reject (error);
@@ -198,3 +195,15 @@ class TokenInterceptor implements InterceptorsWrapper {
198195 handler.next (response);
199196 }
200197}
198+
199+ class _RequestNeedingRetry {
200+ const _RequestNeedingRetry ({
201+ required this .dio,
202+ required this .options,
203+ required this .handler,
204+ });
205+
206+ final Dio dio;
207+ final RequestOptions options;
208+ final ErrorInterceptorHandler handler;
209+ }
0 commit comments