码迷,mamicode.com
首页 > Web开发 > 详细

[RxJS] Implement RxJS `switchMap` by Canceling Inner Subscriptions as Values are Passed Through

时间:2018-09-27 19:44:36      阅读:186      评论:0      收藏:0      [点我收藏+]

标签:tor   event   one   call   round   pip   bsp   col   extend   

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

标签:tor   event   one   call   round   pip   bsp   col   extend   

原文地址:https://www.cnblogs.com/Answer1215/p/9715065.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!