zoukankan      html  css  js  c++  java
  • [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)
  • 相关阅读:
    iphone 图标下载
    iphone 下拉刷新(转)
    技术书评(.NET为主)
    我也设计模式——3.Singleton
    我也设计模式——14.Flyweight
    Web2.0技术研究笔记——1.分类与资源
    我也设计模式——4.Builder
    C#之CLR读书笔记 0
    IMemento 永远置顶
    我也设计模式——21.Memento
  • 原文地址:https://www.cnblogs.com/Answer1215/p/9715065.html
Copyright © 2011-2022 走看看