import 'package:dio/dio.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

/*
 * 用于 UI Page 对应的Controller 混入，可以在关闭页面的时候自动取消网络请求
 * 是否需要使用状态泛型
 */
mixin DioCancelableMixin<T> on AutoDisposeNotifier<T> {
  final CancelToken cancelToken = CancelToken();

  //需要手动的调用取消的注册
  void registerCancellation({void Function()? callback}) {
    ref.onDispose(() {
      callback?.call();

      if (!cancelToken.isCancelled) {
        cancelToken.cancel("Request cancelled due to AutoDisposeNotifier being disposed.");
      }
    });
  }
}
