checkTimeOut<T> static method

Future<T?> checkTimeOut<T>(
  1. Future<T> future,
  2. Duration duration, {
  3. FutureOr<T?> onDone(
    1. T value,
    2. bool isTimeOut
    )?,
})
  • 检查future的执行是否超时 该函数只会在future完成后才会调用onDone并返回结果
  • 注意,部分阻塞会导致startTimeendTimefuture一段时间后返回后仍然相等, 导致isTimeOut永远为false。例如win端调用系统选择文件夹路径接口

Implementation

static Future<T?> checkTimeOut<T>(
  Future<T> future,
  Duration duration, {
  FutureOr<T?> Function(T value, bool isTimeOut)? onDone,
}) async {
  final startTime = DateTime.now().millisecondsSinceEpoch;
  final value = await future;
  if (null == onDone) {
    return value;
  }
  final endTime = DateTime.now().millisecondsSinceEpoch;
  return onDone.call(
    value,
    // 时间差大于限定值
    (endTime - startTime) >= duration.inMilliseconds,
  );
}