RxJS basics − subjects

Subject (https://rxjs-dev.firebaseapp.com/guide/subject) is both Observable and Observer. As Observer, it watches over a data source (for example, a type of event or an external data source) and as Observable, it can be subscribed to, and therefore emit events or values to its subscribers (that is, observers).

Here is an example:

import { Subject } from 'rxjs'; 
 
const observer1 = { 
    next: (value: string) => console.log(`Observer 1: ${value}`) 
}; 
 
const observer2 = { 
    next: (value: string) => console.log(`Observer 1: ${value}`) 
}; 
 
const mySubject = new Subject<string>(); 
 
mySubject.subscribe(observer1); 
mySubject.subscribe(observer2); 
 
mySubject.next("Hello"); 
mySubject.next("World"); 
 
// Output: 
// Observer 1: Hello 
// Observer 2: Hello 
// Observer 1: World 
// Observer 2: World

Previously, the observer1 and observer2 observers get called for each of the next calls on the observed subject.

There are multiple Subject implementations in RxJS: BehaviorSubject, ReplaySubject, AsyncSubject, and many more.

Greatlet's keep going!

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.16.66.206