timeout 抽象方法

Future<T> timeout(
  1. Duration timeLimit, {
  2. FutureOr<T> onTimeout()?,
})

timeLimit经过后停止等待此future。

创建一个新的超时future,如果源future在时间内完成,则与该future具有相同的结果。

如果源future在timeLimit之前未完成,则执行onTimeout操作,并使用其结果(无论它返回还是抛出异常)作为超时future的结果。onTimeout函数必须返回一个T或一个Future<T>。如果onTimeout返回一个future,则使用替代结果future的最终结果来完成超时future,即使源future在替代结果future之前完成。只有源future没有在规定时间内完成这一点才是重要的。

如果省略了onTimeout,超时将导致返回的future以一个TimeoutException来完成。

在任何情况下,源future仍然可以在稍后正常完成。只是它不会用作超时future的结果,除非它在时间限制内完成。即使源future在timeLimit之后完成错误,该错误也会被忽略,就像值结果会被忽略一样。

示例

void main() async {
  var result =
      await waitTask("completed").timeout(const Duration(seconds: 10));
  print(result); // Prints "completed" after 5 seconds.

  result = await waitTask("completed")
      .timeout(const Duration(seconds: 1), onTimeout: () => "timeout");
  print(result); // Prints "timeout" after 1 second.

  result = await waitTask("first").timeout(const Duration(seconds: 2),
      onTimeout: () => waitTask("second"));
  print(result); // Prints "second" after 7 seconds.

  try {
    await waitTask("completed").timeout(const Duration(seconds: 2));
  } on TimeoutException {
    print("throws"); // Prints "throws" after 2 seconds.
  }

  var printFuture = waitPrint();
  await printFuture.timeout(const Duration(seconds: 2), onTimeout: () {
    print("timeout"); // Prints "timeout" after 2 seconds.
  });
  await printFuture; // Prints "printed" after additional 3 seconds.

  try {
    await waitThrow("error").timeout(const Duration(seconds: 2));
  } on TimeoutException {
    print("throws"); // Prints "throws" after 2 seconds.
  }
  // StateError is ignored
}

/// Returns [string] after five seconds.
Future<String> waitTask(String string) async {
  await Future.delayed(const Duration(seconds: 5));
  return string;
}

/// Prints "printed" after five seconds.
Future<void> waitPrint() async {
  await Future.delayed(const Duration(seconds: 5));
  print("printed");
}
/// Throws a [StateError] with [message] after five seconds.
Future<void> waitThrow(String message) async {
  await Future.delayed(const Duration(seconds: 5));
  throw Exception(message);
}

实现

Future<T> timeout(Duration timeLimit, {FutureOr<T> onTimeout()?});