我是响应式(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);
}
我想我理解了一些工具语句,例如 concatMap
、take
、from
等。现在是 .filter (status => Boolean(status))
,那么如果我必须在这个 bool 函数中放入另一个严重的 REST API 请求/通信怎么办,可以有另一个 subscrible()
代码那里。它会破坏这样的过滤器吗?事物(事件)将按什么顺序运行?这个硬件通信是否正常,或者我应该让它不异步(因为它是一个不那么强大的硬件)?
最佳答案
回答你的问题 - 你不能在filter()中放置另一个subscribe()。 (订阅将运行,但不会对过滤器产生任何影响)
如果您想执行另一个异步函数(例如 REST API 调用)来确定要过滤的值,您需要将其与 .flatmap()
运算符链接起来。
关于javascript - 如何将订阅放入 RxJS 或 Angular2 中 Observables 的过滤器中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42036090/