RxJs SwitchMap 学习笔记

简介: 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 click
  switchMap(() => interval(1000))
)
.subscribe(console.log);

image.png

import { Component, OnInit } from '@angular/core';
import { interval, fromEvent, merge, empty } from 'rxjs';
import { switchMap, scan, takeWhile, startWith, mapTo } from 'rxjs/operators';
const COUNTDOWN_SECONDS = 1000;
@Component({
  selector: 'switchMap-study',
  templateUrl: './switchMap.component.html'
})
export class SwitchMapComponent implements OnInit {
    ngOnInit(): void {
    // elem refs
    const remainingLabel = document.getElementById('remaining');
    const pauseButton = document.getElementById('pause');
    const resumeButton = document.getElementById('resume');
    // streams
    const interval$ = interval(1000).pipe(mapTo(-1));
    const pause$ = fromEvent(pauseButton, 'click').pipe(mapTo(false));
    const resume$ = fromEvent(resumeButton, 'click').pipe(mapTo(true));
    const timer$ = merge(pause$, resume$).pipe(
        startWith(true),
        switchMap(val => (val ? interval$ : empty())),
        scan((acc, curr) => (curr ? curr + acc : acc), COUNTDOWN_SECONDS),
        takeWhile(v => v >= 0)).subscribe((val: any) => (remainingLabel.innerHTML = val));
    }
}
<h1>Switch Map Study</h1>
<a href="https://www.learnrxjs.io/learn-rxjs/operators/transformation/switchmap">Document</a>
<h4>
    Time remaining: <span id="remaining"></span>
    </h4>
    <button id="pause">
    Pause Timer
    </button>
    <button id="resume">
    Resume Timer
</button>

image.png

image.png

注意 empty() 的用法,返回一个类型为 never 的 Observable.


Creates an Observable that emits no items to the Observer and immediately emits a complete notification.


Just emits ‘complete’, and nothing else.


This static operator is useful for creating a simple Observable that only emits the complete notification. It can be used for composing with other Observables, such as in a mergeMap.


单步调试点了 pause 之后:

image.png

image.pngimage.png

image.png


相关文章
|
5月前
|
JavaScript 前端开发 调度
15_Rxjs
15_Rxjs
46 0
Rxjs map, mergeMap 和 switchMap 的区别和联系
Rxjs map, mergeMap 和 switchMap 的区别和联系
|
JavaScript 前端开发 调度
你会用RxJS吗?【初识 RxJS中的Observable和Observer】
概念 RxJS是一个库,可以使用可观察队列来编写异步和基于事件的程序的库。 RxJS 中管理和解决异步事件的几个关键点: Observable: 表示未来值或事件的可调用集合的概念。 Observer: 是一个回调集合,它知道如何监听 Observable 传递的值。 Subscription: 表示一个 Observable 的执行,主要用于取消执行。 Operators:** 是纯函数,可以使用函数式编程风格来处理具有map、filter、concat、reduce等操作的集合。
138 0
|
前端开发 JavaScript API
Rxjs源码解析(一)Observable
学习一个库最好的方法就是看其源码,理解其 api 的调用原理,用起来自然也就很清楚自己到底在干什么了,秉持着此观念,为了更好地理解 rxjs,抽空将其源码看了一遍 本文章不会刻意涉及概念性的东西,主线就是解读源码,并在恰当的时候给出一些小例子,源码基于 rxjs v7.4.0 版本
319 0
|
安全 数据库
RxJs SwitchMap 学习笔记
RxJs SwitchMap 学习笔记
183 0
RxJs SwitchMap 学习笔记
|
调度
rxjs switchMap的实现原理
rxjs switchMap的实现原理
139 0
rxjs switchMap的实现原理
|
Web App开发 存储 JSON
RxJS switchMap, mergeMap, concatMap,exhaustMap 的比较
RxJS switchMap, mergeMap, concatMap,exhaustMap 的比较
155 0
RxJS switchMap, mergeMap, concatMap,exhaustMap 的比较
rxjs里switchMap operators的用法
rxjs里switchMap operators的用法
190 0
rxjs里switchMap operators的用法
|
设计模式
Rxjs 的一些学习笔记
Rxjs 的一些学习笔记
137 0
Rxjs 的一些学习笔记