retrofit.dart icon indicating copy to clipboard operation
retrofit.dart copied to clipboard

@CancelRequest can't be used together with @DioOptions

Open Tumist76 opened this issue 2 years ago • 1 comments

I need to override receiveTimeout for single request and have an option to cancel a request, because I'm downloading a file. For this, I use both @CancelRequest and @DioOptions annotations in request. In this combination, Retrofit doesn't include cancelToken in RequestOptions.

To Reproduce Steps to reproduce the behavior:

  1. Open example/lib/example.dart from Retrofit's example.
  2. Add @DioOptions to cancelRequest annotation.
  3. Run build_runner
  4. Check generated dio request in example.g.dart.

Generated code You can see in the following generated code that cancelToken isn't used.

  @override
  Future<String> cancelRequest(
    options,
    cancelToken,
  ) async {
    const _extra = <String, dynamic>{};
    final queryParameters = <String, dynamic>{};
    final _headers = <String, dynamic>{};
    final _data = <String, dynamic>{};
    final newOptions = newRequestOptions(options);
    newOptions.extra.addAll(_extra);
    newOptions.headers.addAll(_dio.options.headers);
    newOptions.headers.addAll(_headers);
    final _result = await _dio.fetch<String>(newOptions.copyWith(
      method: 'GET',
      baseUrl: baseUrl ?? _dio.options.baseUrl,
      queryParameters: queryParameters,
      path: '/cancel',
    )..data = _data);
    final value = _result.data!;
    return value;
  }

Additional context The problem is present in latest pub.dev version (retrofit: v3.3.1, generator: 4.2.0) and in master branch of repository.

Tumist76 avatar Jan 23 '23 05:01 Tumist76

Hey @Tumist76,

In your case, you don't need the @CancelToken annotation, since your @DioOptions can take options of type RequestOptions and this class itself has a parameter cancelToken

like so:

@RestApi()
abstract class Api {
  factory Api(Dio dio, {String baseUrl}) = _Api;

  @GET('path')
  Future<void> getTest(
    @DioOptions() RequestOptions options,
  );
}

And then, you can use it like so:

final dio = Dion();
final cancelToken = CancelToken();

Api(dio).getTest(
  RequestOptions(
    path: 'your/path',
    cancelToken: cancelToken
  ),
);

Hope this helps you out, Please consider closing the issue if you found this solution is what you exactly need!

devmuaz avatar Feb 12 '23 16:02 devmuaz