Dio Cancel current running API before starting a new API request

Viewed 2807

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;
    }}}
1 Answers

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: canceToken);

  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!

Related