天天看點

RxJs SwitchMap 學習筆記

The main difference between switchMap and other flattening operators is the cancelling effect. On each emission the previous inner observable (the result of the function you supplied) is cancelled and the new observable is subscribed. You can remember this by the phrase switch to a new observable.

switchMap 和其他扁平化操作符的主要差別在于取消效果。 在每次發射時,先前的内部 observable(您提供的函數的結果)被取消并訂閱新的 observable。 您可以通過短語 switch to a new observable 記住這一點。

This works perfectly for scenarios like typeaheads where you are no longer concerned with the response of the previous request when a new input arrives. This also is a safe option in situations where a long lived inner observable could cause memory leaks, for instance if you used mergeMap with an interval and forgot to properly dispose of inner subscriptions. Remember, switchMap maintains only one inner subscription at a time, this can be seen clearly in the first example.

這對于像預先輸入這樣的場景非常有效,當新輸入到達時,您不再關心先前請求的響應。 在長期存在的内部 observable 可能導緻記憶體洩漏的情況下,這也是一個安全的選擇。

Be careful though, you probably want to avoid switchMap in scenarios where every request needs to complete, think writes to a database. switchMap could cancel a request if the source emits quickly enough. In these scenarios mergeMap is the correct option.

但是要小心,您可能希望在每個請求都需要完成的情況下避免使用 switchMap,比如寫入資料庫的場景。 如果源發出足夠快,switchMap 可以取消請求。 在這些情況下,mergeMap 是正确的選項。

看這個例子:

import { interval, fromEvent } from 'rxjs';
import { switchMap } from 'rxjs/operators';

fromEvent(document, 'click')
.pipe(
  // restart counter on every click
  switchMap(() => interval(1000))
)
.subscribe(console.log);
      

每次點選螢幕之後,fromEvent issue 出來的 MouseEvent,傳入 switchMap 内部,都會重新開機一個新的時間間隔為1秒的計時器,并且取消之前的定時器。列印如下:

RxJs SwitchMap 學習筆記