javascript - `reduce/scan` 的累加器函数中的可观察类型是否匹配?

标签 javascript rxjs

我想将我的应用程序状态写为 对所有输入可观察量进行reduce(或更确切地说scan)函数。

const inputStream$ =
  Rx.Observable.merge(all$, observables$, Im$, interested$, in$);

const outputStream$ = inputStream$.scan(accumulator, initialState);

由于 inputStream$ 可以包含任何值,因此 accumulator 函数 必须进行大量类型检查,这看起来相当脆弱。

我正在寻找的是这样的:

function accumulator (acc, x) {
  switch (x) {
    case "all$ has fired":
      return newState0;
    case "observables$ has fired":
      return newState1;
    case "Im$ has fired":
      return newState2;
    case "interested$ has fired":
      return newState3;
    case "in$ has fired":
      return newState4;

} }

这可能吗?

最佳答案

当然。只需将 map 运算符应用于每个输入流,即可在合并之前向该值添加鉴别器:

Rx.Observable.prototype.tag = function (tag) {
    return this.map(value => ({ tag, value }));
};

const inputStream$ = Rx.Observable.merge(a.tag("a"), b.tag("b"), ...);
const outputStream$ = inputStream$.scan(v => {
        const value = v.value;
        switch (v.tag) {
            case "a": return newState0;
            case "b": return newState1;
            ...
        }
    }, initialState);

关于javascript - `reduce/scan` 的累加器函数中的可观察类型是否匹配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32186726/

相关文章:

Angular:Observable 在使用管道和选项卡时改变行为

angular - 如何从返回 JSON 数组的 Angular http get 填充 html 表

javascript - 在 mousedown 处理程序中更改可见性属性时,不会在 Safari 或 Firefox 中触发单击处理程序

javascript - chrome 设置的不透明度未按预期一致渲染

javascript - Nodemailer 和 Node 中的密码问题

javascript - rxjs - 丢弃 future 返回的可观察对象

带有 rxjs 的 angular2 http 中间件

javascript - d3 鼠标事件 : using selection. 节点()

javascript - 用文本替换图像

javascript - 如何在执行期间使用 rxjs 向 Inquirer JS 动态添加问题?