reactive-programming - Rxjs)有选择地取消订阅 flatMap 中的可观察量

标签 reactive-programming rxjs

有没有办法在 flatMapconcatMap 操作完成之前取消/删除单个可观测值?

我目前有一个可观察的触发 API 请求的 UI 操作,为此我使用 flatMap:

actionsFromUI.flatMap(a => http.request("blah?id=" + a.id))

然后订阅渲染结果。它的一个非常好的特性是,如果我取消订阅,所有正在进行的 API 请求都会自动取消。我不想打破这一点。

现在我想支持可以取消特定正在进行的请求的 UI 操作。 UI 操作可以触发特定 ID 的 API 请求,然后后续 UI 操作可以取消该 ID 的 API 请求。

我希望这个虚拟代码能够说明我想要做的事情:

let actions = [
    { action: "start", id: 1 },
    { action: "start", id: 2 },
    { action: "start", id: 3 },
    { action: "cancel", id: 1 },
    { action: "start", id: 4 },
    { action: "cancel", id: 3 },
    { action: "start", id: 1 }
];

Observable.from(actions)
    .flatMap(a => {
        if (a.action === "start") {
            return http.request("blah?id=" + a.id);
        } else if (a.action === "cancel") {
            // ???
        }
    })
    .subscribe(response => {
        console.log(response);
    });

最佳答案

是的,有办法做到这一点。

您可以使用 takeUntil 运算符来实现此目的。

有些人会这样想:

// actions - observable of user actions, each action has id field
// cancelActions - observable of action cancelations each has id of action to cancel
// doRequest - function that starts request and returns observable

const results = actions.flatMap(
  action => doRequest(action)
    .takeUntil(
      cancelActions.filter(cancel => cancel.id === action.id)
    )
);

https://github.com/Reactive-Extensions/RxJS/blob/master/doc/api/core/operators/takeuntil.md

关于reactive-programming - Rxjs)有选择地取消订阅 flatMap 中的可观察量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38347539/

相关文章:

c# - 使用 Reactive Extensions (RX),是否可以添加 "Pause"命令?

angular - 多个 Observable 订阅

vue.js - 如何将 RSocket 数据检索到不同的选项卡?

javascript - 有效地创建从可观察集合中过滤特定项目的可观察对象

javascript - Bacon.js 总线的 RxJS 等价物是什么?

ios - 使用 RxSwift 在 x 秒后显示事件指示器

reactive-programming - Rx swift 在使用 flatMap 后保持原始流的原始顺序

angular - 如何在 Angular 中重新加载可观察的 http?

angular - 在 Angular rxjs 中,我什么时候应该使用 `pipe` 与 `map`

javascript - RxJS Observable :'Skip is not a function'(或任何其他函数)