Dio Cancel current running API before starting a new API request
771
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!
Author by
Avnish Nishad
Updated on December 31, 2022Comments
-
Avnish Nishad over 1 year
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; }}}
-
Avnish Nishad over 2 yearsWhere should I use cancelToken.cancel(); @Jigar
-
Jigar Fumakiya over 2 years@Avnishkumar when you make another API request call you need to cancel the previous one.
-
Avnish Nishad over 2 yearsI 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);
-
Jigar Fumakiya over 2 yearsYou need to use await Token().homescreenToken.cancel(); cancel() is future.
-
Avnish Nishad over 2 yearsCancel() is not Future while its return type is void, so I cannot use await
-
Jigar Fumakiya over 2 years@Avnishkumar then you are missing something please debug the code.
-
Avnish Nishad over 2 yearsCan you connect me on any desk or team viewer ,please It won't take much time
-
Jigar Fumakiya over 2 yearsLet us continue this discussion in chat.