dio icon indicating copy to clipboard operation
dio copied to clipboard

[Interceptor] How do I implement retry interceptor within attempt count?

Open devnta opened this issue 2 years ago • 3 comments

Firstly, I'm sorry because my english is not good. I'm trying implement retry interceptor. Mean, when countAttempt reach to maxAttempt, it is will stop. Mean, in code:

if(countAttempt <= maxAttempt){
countAttempt++;
doRetry();
}else{
//Stop.
}

I have BaseInterceptor:

abstract class BaseInterceptor extends InterceptorsWrapper {
  int get maxAttempt => 3;

  late Future Function() future;

  BaseInterceptor(this.future);

  int countAttempt = 0;

  @override
  void onError(DioError err, ErrorInterceptorHandler handler) async {
    super.onError(err, handler);
    Logger().e("Found an error $countAttempt");
    if (countAttempt <= maxAttempt) {
      countAttempt++;
      await future();
    }
  }

  @override
  void onResponse(Response response, ResponseInterceptorHandler handler) {
    super.onResponse(response, handler);
    print("onResponse triggered");
  }

  @override
  void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
    super.onRequest(options, handler);
    print("onRequest triggered");
  }
}

and RetryInterceptor extends above class:

class RetryInterceptor extends BaseInterceptor {
 RetryInterceptor({required Future Function() future}) : super(future);

 @override
 int get maxAttempt => 5;
}

Finally, I using:

class UserRepository implements IUserRepository {
@override
Future<Model> getUser({int page = 1}) async {
  final dio = Dio();
  dio.interceptors.add(RetryInterceptor(future: getUser)); //This
  Response response;
  response = await dio.get('https://reqres.in/api/users',
      queryParameters: {'per_page': 10, 'page': page});
  final user = Model.fromJson(response.data);
  return user;
}
}

My problem is countAttempt always is 0 that cause retry called infinity. I tried combine singleton but it seem not suitable. What the way I can do it?

devnta avatar May 13 '22 01:05 devnta

@NTA-trongpq try this package dio_smart_retry

dhruvanb avatar May 25 '22 04:05 dhruvanb

@dhruvanb Thank you so much. This is exactly what I'm looking for.

devnta avatar May 26 '22 01:05 devnta

@dhruvanb Thank you so much. This is exactly what I'm looking for.

Welcome

dhruvanbhalara avatar May 26 '22 07:05 dhruvanbhalara