三种方式
- 转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',
);
有哪些场景?
以下是我遇到的场景
- 固件升级过程的中途取消
- 设备滚轮控制角度 需要去抖且需要保证最后一条角度数据能够生效
网友评论