[RxJS] Implement RxJS `switchMap` by Canceling Inner Subscriptions as Values are Passed Through(代码片段

Posted Answer1215

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[RxJS] Implement RxJS `switchMap` by Canceling Inner Subscriptions as Values are Passed Through(代码片段相关的知识,希望对你有一定的参考价值。

switchMap is mergeMap that checks for an "inner" subscription. If the "inner" subscription exists, switchMap unsubscribes from that "inner" subscription which effectively "cancels" any pending pushes.

 

import { fromEvent, of, Subscriber } from "rxjs"
import {
  scan,
  delay,
  mergeMap,
  switchMap
} from "rxjs/operators"

class MySwitchMapSubscriber extends Subscriber {
  innerSubscription

  constructor(sub, fn) {
    super(sub)

    this.fn = fn
  }

  _next(value) {
    console.log(`outer`, value)
    const o$ = this.fn(value)

    if (this.innerSubscription) {
      this.innerSubscription.unsubscribe()
    }

    this.innerSubscription = o$.subscribe({
      next: value => {
        console.log(`  inner`, value)
        this.destination.next(value)
      }
    })
  }
}

const mySwitchMap = fn => source =>
  source.lift({
    call(sub, source) {
      source.subscribe(
        new MySwitchMapSubscriber(sub, fn)
      )
    }
  })

const observable$ = fromEvent(
  document,
  "click"
).pipe(
  scan(i => i + 1, 0),
  mySwitchMap(value => of(value).pipe(delay(500)))
)

const subscriber = {
  next: value => {
    console.log(value)
  },
  complete: () => {
    console.log("done")
  },
  error: value => {
    console.log(value)
  }
}

observable$.subscribe(subscriber)

 

以上是关于[RxJS] Implement RxJS `switchMap` by Canceling Inner Subscriptions as Values are Passed Through(代码片段的主要内容,如果未能解决你的问题,请参考以下文章

[RxJS] Implement RxJS `switchMap` by Canceling Inner Subscriptions as Values are Passed Through(代码片段

如何理解 RxJS?RxJS的中文API和使用教程

rxjs-tslint vs rxjs-tslint-rules 包

RxJS 6有哪些新变化?

如何在不需要 rxjs-compat 的情况下只导入 RxJS 6 中使用的运算符,如旧的 RxJS?

RxJS入门2之Rxjs的安装