簡體   English   中英

如何在RxJS或Angular2中的Observables中的過濾器中添加訂閱?

[英]How to put subscribes in a filter in Observables in RxJS or 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()中添加另一個subscribe()。 (訂閱將運行但不會對過濾器產生任何影響)

如果要執行另一個異步函數(例如REST API調用)來確定要過濾的值,則需要使用.flatmap()運算符對其進行鏈接。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM