日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) >

RxJs SwitchMap 学习笔记

發(fā)布時(shí)間:2023/12/19 28 豆豆
生活随笔 收集整理的這篇文章主要介紹了 RxJs SwitchMap 学习笔记 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

網(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)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。