• [RxJS] Share data among multiple subscribers with Subjects


    Subject as resource can be shared amount multi observers.

    Normal Observable pattern is Cold observable, each subscription will get its own resource:

    import { interval, Subject } from "rxjs";
    import { tap } from "rxjs/operators";
    
    const observer = {
      next: (val) => console.log("next", val),
      error: (err) => console.error("error", err),
      complete: () => console.log("complete"),
    };
    
    const subject = new Subject();
    
    const interval$ = interval(2000).pipe(
      tap((val) => console.log("new interval", val))
    );
    
    // Each subscription is getting its own interval
    // rather than one interval being shared between both
    interval$.subscribe(observer);
    interval$.subscribe(observer);

    When we swtich to Subject:

    import { interval, Subject } from "rxjs";
    import { tap } from "rxjs/operators";
    
    const observer = {
      next: (val) => console.log("next", val),
      error: (err) => console.error("error", err),
      complete: () => console.log("complete"),
    };
    
    const subject = new Subject();
    
    const interval$ = interval(2000).pipe(
      tap((val) => console.log("new interval", val))
    );
    /*
    // Each subscription is getting its own interval
    // rather than one interval being shared between both
    interval$.subscribe(observer);
    interval$.subscribe(observer);
    */
    
    const subscription = subject.subscribe(observer);
    const subscriptionTwo = subject.subscribe(observer);
    // Interval only got log out once
    // And next value log out twice by two subscirptions
    // Subject is multicasting, sharing the observable
    // It is useful when you have expanse resourse such as 
    // Web stock socket$.subscribe(subject)
    interval$.subscribe(subject);

    Well, there is easier way to achieve the same effect by using share():

    import { interval } from "rxjs";
    import { share, shareReplay, tap } from "rxjs/operators";
    
    const observer = {
      next: (val) => console.log("next", val),
      error: (err) => console.error("error", err),
      complete: () => console.log("complete"),
    };
    
    const interval$ = interval(2000).pipe(
      tap((val) => console.log("new interval", val)),
      share()
    );
    
    interval$.subscribe(observer);
    interval$.subscribe(observer);

  • 相关阅读:
    异常:Unknown lifecycle phase "mvn". You must specify a valid lifecycle
    java中数的表示
    windows7 桌面突然卡住了,点击右键点不了,点击桌面软件点不了,怎么办?
    DJango错误日志生成
    drf框架接口文档
    drf框架中分页组件
    UVa10234 Race
    洛谷P2982 [USACO10FEB]慢下来Slowing down
    UVa10820 Send a Table
    POJ1861 Network
  • 原文地址:https://www.cnblogs.com/Answer1215/p/16697966.html
Copyright © 2020-2023  润新知