2

what is the useful thing for "Subscribe providing subject" and what does this mean:- 1- why I use subscribe providing subject

import { Subject, from } from 'rxjs';
 
const subject = new Subject<number>();
 
subject.subscribe({
  next: (v) => console.log(`observerA: ${v}`)
});
subject.subscribe({
  next: (v) => console.log(`observerB: ${v}`)
});
 
const observable = from([1, 2, 3]);
 
observable.subscribe(subject); // You can subscribe providing a Subject
 
// Logs:
// observerA: 1
// observerB: 1
// observerA: 2
// observerB: 2
// observerA: 3
// observerB: 3
R. Richards
  • 24,603
  • 10
  • 64
  • 64

1 Answers1

2

You subscribe to an RxJS Observable with an Observer. This is the typescript interface for an observer.

interface Observer<T> {
  closed?: boolean;
  next: (value: T) => void;
  error: (err: any) => void;
  complete: () => void;
}

or a partial observer (just implement some of the callbacks) or with a function (which is the same as a partial observer with just the next callback.

It turns out that a Subject implements the Observer interface and so it can be used as an observer! This is a simple way to multicast a observable (and how the multicasting operators work to an extent).

Mrk Sef
  • 7,557
  • 1
  • 9
  • 21