首页 > 解决方案 > 如何使用 CancelableOperation 取消未来的链接

问题描述

我无法理解 dart async CancelableOperation.fromFuture 的工作原理。它似乎取消了第一个未来,但 .then 总是被执行。

在使用套接字时,我需要取消连接操作以避免等待套接字超时。

final op = f1
        .then((_) => f2);

    _connectOperation = CancelableOperation.fromFuture(op,
        onCancel: () => throw CustomException());

    return _connectOperation.valueOrCancellation();

f1 被取消,但 f2 仍被执行。

标签: asynchronousdart

解决方案


内部发生的任何事情op都不会受到任何影响。Future 没有用于向其传达取消意图的接口。

仅成功操作可应用于_connectOperation.

_connectOperation = CancelableOperation.fromFuture(f1)
   .then(
      (value) => f2, // only runs if not cancelled
      onCancel: () => throw CustomException()
    );

推荐阅读