javascript - 如何将订阅放入 RxJS 或 Angular2 中 Observables 的过滤器中?

标签 javascript angular asynchronous rxjs observable

我是响应式(Reactive)编程的新手,试图理解这里的想法。我遇到问题 here似乎已经解决了,但给我留下了更多问题,其中之一就是过滤器。这是我从 olsn 的答案中借用的一些代码,

function myLoop(item_array) {
    return Observable.from(item_array)
        // if you don't mind the execution-order you can use "mergeMap" instead of "concatMap"
        .concatMap(item => configHardwareMock(item)
            .switchMap(resultId => Observable.interval(500)
                .do(() => console.info("Checking status of: " + resultId))
                .switchMap(() => intervalCheckingStatus(resultId))
                .filter(status => Boolean(status)) // your logic if the status is valid, currently just a boolean-cast
                .take(1) // and complete after 1 value was valid
                .mapTo(item) // map back to "item" so we can notify the subscriber (this is optional I guess and depends on if you want this feature or not)
            )
        );
}

//an example of such boolean from olsn
function intervalCheckingStatus(resultId) {
  if (Math.random() < .4) {
    return Observable.of(false);
  }

  return Observable.of(true);
}

我想我理解了一些工具语句,例如 concatMaptakefrom 等。现在是 .filter (status => Boolean(status)),那么如果我必须在这个 bool 函数中放入另一个严重的 REST API 请求/通信怎么办,可以有另一个 subscrible() 代码那里。它会破坏这样的过滤器吗?事物(事件)将按什么顺序运行?这个硬件通信是否正常,或者我应该让它不异步(因为它是一个不那么强大的硬件)?

最佳答案

回答你的问题 - 你不能在filter()中放置另一个subscribe()。 (订阅将运行,但不会对过滤器产生任何影响)

如果您想执行另一个异步函数(例如 REST API 调用)来确定要过滤的值,您需要将其与 .flatmap() 运算符链接起来。

关于javascript - 如何将订阅放入 RxJS 或 Angular2 中 Observables 的过滤器中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42036090/

相关文章:

Angular hash 和 path 策略一起——混合模式

javascript - Firefox 不会在动态脚本注入(inject)时加载 "asynchronous"?

java - 在主线程中执行异步 lambda?

javascript - 使 javascript 的 Replace() 匹配多个单词

javascript - a.map 不是函数错误 nvd3 和 ng-repeat

javascript - 导入/导出 HTML5 localStorage 数据

asynchronous - 如何在webpack中加载远程文件

javascript - 更改默认滚动条行为

angular - 当快速拖动光标时会丢失元素 - Angular

html - 如何使用 HTML 在 Ionic2 toasts 中添加新行?