简体   繁体   English

如何在RxJS或Angular2中的Observables中的过滤器中添加订阅?

[英]How to put subscribes in a filter in Observables in RxJS or Angular2?

I'm new to reactive programming, trying to understand the idea here. 我是反应式编程的新手,试图在这里理解这个想法。 I got a problem here and it seems solved, but leaving me more questions, one of them is the filter. 我在这里遇到了一个问题似乎已经解决了,但是给我留下了更多问题,其中一个就是过滤器。 Here is some code I borrowed from olsn's answer, 这是我从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);
}

I think I understood some of the tool statements like concatMap , take , from etc. Now it is the .filter(status => Boolean(status)) , so what if I have to put another serious of REST API requests/communication in this boolean function, there can be another subscrible() code in there. 我想我理解了一些工具语句,比如concatMaptakefrom等。现在它是.filter(status => Boolean(status)) ,那么如果我必须在这里放置另一个严重的REST API请求/通信呢?布尔函数,那里可以有另一个subscrible()代码。 Will it break such a filter? 它会破坏这样的过滤器吗? In what order the things(events) will run? 事物(事件)将以什么顺序运行? Is this hardware communication normal, or I should have make it not async (since it is a hardware not that powerful) ? 这个硬件通信是否正常,或者我应该让它不是异步(因为它是一个不那么强大的硬件)?

To answer your question - you cannot put another subscribe() in the filter(). 要回答你的问题 - 你不能在filter()中添加另一个subscribe()。 (subscribe will run but will not have any effect on the filter) (订阅将运行但不会对过滤器产生任何影响)

If you want to perform another async function (eg REST API call) to determine what values to filter you will need to chain it with a .flatmap() operator. 如果要执行另一个异步函数(例如REST API调用)来确定要过滤的值,则需要使用.flatmap()运算符对其进行链接。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM