Dart 中断Future

北慕城南 提交于 2020-02-22 15:49:37

中断future

方法1)

import 'package:async/async.dart';

void main() {
  var get = CancelableOperation.fromFuture(
    Future.delayed(Duration(seconds: 3)),
    onCancel: () => print('onCancel'),
  );

  get.value.then(print);
  Future.delayed(Duration(seconds: 1)).then((_) => get.cancel());
}

方法2)

import 'package:async/async.dart';

void main() {
  var completer = CancelableCompleter(onCancel: () => print('onCancel'));
  completer.complete(Future.delayed(Duration(seconds: 3))); // 添加future
  completer.operation.value.then(print);// 订阅future
  Future.delayed(Duration(seconds: 1)).then((_) => completer.operation.cancel());//中断future
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!