javascript - 用于稍后提取值的可观察运算符

标签 javascript rxjs reactive-programming

我正在将可观察量与 RXJS 库一起使用,并且遇到一种情况,我想提取一个值并在未来某个未指定的时间(不是下一个运算符或订阅方法)使用它。

我目前正在通过每个操作传递该值,直到我需要它为止。看起来像这样的东西:

obsveable$.pipe(
    ofType('example'),
    map((action) => [
        action, // <-- passing this through
        somethingElse
    ]),
    map(([action, other]) => [
        action, // <-- through again
        anotherThing
    ]),
    map(([action, other]) => {
        // finally use action
    }),
);

我也许可以尝试将其保存到局部变量中 - 像这样:

let action;
obsveable$.pipe(
    ofType('example'),
    map((_action) => action = _action),
    map((action) => action.somethingElse),
    map((other) => {
        // finally use action
    })
);

这两种解决方案都不是最优的。当有很多步骤时,第一个会变得笨拙,第二个可能会出现操作顺序问题(并且它没有使用很酷的 react 方法)。

还有哪些其他选择?

最佳答案

您可以通过以下方式创建一个闭包:

obsveable$.pipe(
    ofType('example'),
    mergeMap(action => 
        Observable.of(somethingElse)
            .pipe(
                map(other => anotherThing), 
                map(other => { 
                    // use action
                })
            )
    )
);

关于javascript - 用于稍后提取值的可观察运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49212159/

相关文章:

Angular,错误拦截器,在不同的 url 上重试原始请求

ios - ReactiveX 如何暂停 observable

javascript - 从 RxJS promise 流

angular - 为什么我会得到多个 Observables?

java - Rxjava : How to combine multiple observables without all observables completing?

javascript - jQuery 淡入淡出在 Google Chrome 中无法正常工作

javascript - 如何解决 Safari 10.1 错误 "Failed to send WebSocket frame"?

javascript - react : How to prevent an integer value turning to NaN after form submit

c# - 将模型分配给 Razor 中的 Javascript 变量

angular - 在 NGXS 中组合多个 @Select