RxJs SwitchMap 学习笔记
網(wǎng)址: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 和其他扁平化操作符的主要區(qū)別在于取消效果。 在每次發(fā)射時(shí),先前的內(nèi)部 observable(您提供的函數(shù)的結(jié)果)被取消并訂閱新的 observable。 您可以通過短語(yǔ) switch to a new observable 記住這一點(diǎn)。
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.
這對(duì)于像預(yù)先輸入這樣的場(chǎng)景非常有效,當(dāng)新輸入到達(dá)時(shí),您不再關(guān)心先前請(qǐng)求的響應(yīng)。 在長(zhǎng)期存在的內(nèi)部 observable 可能導(dǎo)致內(nèi)存泄漏的情況下,這也是一個(gè)安全的選擇。
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.
但是要小心,您可能希望在每個(gè)請(qǐng)求都需要完成的情況下避免使用 switchMap,比如寫入數(shù)據(jù)庫(kù)的場(chǎng)景。 如果源發(fā)出足夠快,switchMap 可以取消請(qǐng)求。 在這些情況下,mergeMap 是正確的選項(xiàng)。
看這個(gè)例子:
import { interval, fromEvent } from 'rxjs'; import { switchMap } from 'rxjs/operators';fromEvent(document, 'click') .pipe(// restart counter on every clickswitchMap(() => interval(1000)) ) .subscribe(console.log);每次點(diǎn)擊屏幕之后,fromEvent issue 出來(lái)的 MouseEvent,傳入 switchMap 內(nèi)部,都會(huì)重啟一個(gè)新的時(shí)間間隔為1秒的計(jì)時(shí)器,并且取消之前的定時(shí)器。打印如下:
總結(jié)
以上是生活随笔為你收集整理的RxJs SwitchMap 学习笔记的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: RxJS mergeMap 学习笔记
- 下一篇: 女子酒店用吹风机吹头发:竟喷出7厘米长火