如何将订阅放入 RxJS 或 Angular2 中可观察量的过滤器中



我是响应式编程的新手,试图理解这里的想法。我在这里遇到了一个问题,它似乎解决了,但给我留下了更多问题,其中之一是过滤器。这是我从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)),那么如果我必须在这个布尔函数中放置另一个严肃的 REST API 请求/通信怎么办,那里可以有另一个subscrible()代码。它会打破这样的过滤器吗?事物(事件(将按什么顺序运行?这种硬件通信是正常的,还是我应该让它不异步(因为它是一个功能不强大的硬件(?

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

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

最新更新