[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);

 

posted @ 2022-09-15 21:06  Zhentiw  阅读(31)  评论(0编辑  收藏  举报