RxJs SwitchMap 学习笔记
網址:https://www.learnrxjs.io/learn-rxjs/operators/transformation/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 clickswitchMap(() => interval(1000)) ) .subscribe(console.log);每次點擊屏幕之后,fromEvent issue 出來的 MouseEvent,傳入 switchMap 內部,都會重啟一個新的時間間隔為1秒的計時器,并且取消之前的定時器。打印如下:
總結
以上是生活随笔為你收集整理的RxJs SwitchMap 学习笔记的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: RxJS mergeMap 学习笔记
- 下一篇: 女子酒店用吹风机吹头发:竟喷出7厘米长火