Dio Cancel current running API before starting a new API request
Asked Answered
A

1

8

I am using DIO package for API request but the issue is that when I request for another API while the first API is still in progress.

It doesn't cancel the first request. Both the APIs run simultaneously which is not the desired in my app scenario.

class DioClient {

 static BaseOptions options = BaseOptions(baseUrl: baseUrl);

   Dio _dio = Dio(options);

   Future<dynamic> postFormData(
      {dynamic data, String url, dynamic header}) async {
    final data1 = data;
    var formData = FormData.fromMap(data1);

    try {
      var response = await _dio.post(url,
          options: Options(headers: header), data: formData);

      return response.data;
    } catch (e) {
      throw e;
    }}}
Aric answered 23/8, 2021 at 5:17 Comment(0)
E
14

If you want to cancel the API request call then you need to use the cancel token provided by DIO.

You need to pass cancel token in dio request when you make other API call use that cancel token to cancel the API request

Here is the code

class DioClient {
 static BaseOptions options = BaseOptions(baseUrl: baseUrl);
     
  // Here is line you need
  CancelToken cancelToken = CancelToken();
  Dio _dio = Dio(options);
    
  Future<dynamic> postFormData({
    dynamic data, 
    String url, 
    dynamic header,
  }) async {
    final data1 = data;
    var formData = FormData.fromMap(data1);
    
    try {
      // Pass cancel token here
      var response = await _dio.post(
        url,
        options: Options(headers: header), 
        data: formData,
        cancelToken: cancelToken,
      );
      return response.data;
    } catch (e) {
      throw e;
    }
  }
}

And use that cancelToken to cancel the API request when you call another API first you cancel the previous request.

cancelToken.cancel();

Enjoy!

Expediential answered 23/8, 2021 at 5:44 Comment(8)
Where should I use cancelToken.cancel(); @JigarAric
@Avnishkumar when you make another API request call you need to cancel the previous one.Expediential
I put cancel token in globals class and and cancel the token before starting a new request Token().homescreenToken.cancel(); final _result = await DioClient().postFormData(header: { "Authorization": globals.token, "content-type": "application/json", }, data: data, url: url, cancelToken: Token().homescreenToken);Aric
You need to use await Token().homescreenToken.cancel(); cancel() is future.Expediential
Cancel() is not Future while its return type is void, so I cannot use awaitAric
@Avnishkumar then you are missing something please debug the code.Expediential
Can you connect me on any desk or team viewer ,please It won't take much timeAric
Let us continue this discussion in chat.Expediential

© 2022 - 2024 — McMap. All rights reserved.