Dart 如何取消future

三种方式

  • 转Stream
StreamSubscription? a= setSprayWithWheelWithFuture().asStream().listen((event) {
            setSprayWithWheel(right, isForce: true);
          };

a?.canel();

Future setSprayWithWheelWithFuture() async {
    await Future.delayed(Duration(seconds: 1));
  }
  • CancelableOperation
    需要依赖async
await setSprayWithWheelFuture?.cancel();
setSprayWithWheelFuture = CancelableOperation.fromFuture(setSprayWithWheelWithFuture(right));
int? value = await setSprayWithWheelFuture?.value;
print('setSprayWithWheelFuture::value=$value'); //cancel 后 这行之后的代码不会执行 实现原理猜测是寄存器存储了当前执行的位置 类似协程概念
if (value != null) {
setSprayWithWheel(right, isForce: true);
}
  • timeout
    没有上述两种方式灵活以及支持场景不丰富
setSprayWithWheelWithFuture().timeout(
      const Duration(seconds: 1),
      onTimeout: () =>
          'The process took too much time to finish. Please try again later',
);

有哪些场景?
以下是我遇到的场景

  • 固件升级过程的中途取消
  • 设备滚轮控制角度 需要去抖且需要保证最后一条角度数据能够生效
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 首先要明确的一点是, 在dart协程式的编程语言中, 是无法中断一个Future的执行的, 我们所能做的只能是取消...
    伊犁娃娃阅读 11,354评论 1 1
  • 取消Future的方法,通过百度搜索得到答案,将future转为stream,stream中有取消的方法,可以取消...
    木叶zhaojie阅读 7,319评论 0 2
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 136,088评论 19 139
  • What's the point?Dart code runs in a single “thread” of e...
    MakerChin阅读 12,082评论 2 5
  • 本节介绍各种常见的浏览器事件。 鼠标事件 鼠标事件指与鼠标相关的事件,主要有以下一些。 click 事件,dblc...
    许先生__阅读 7,548评论 0 4

友情链接更多精彩内容