In RxJS, when you want to manually emit values, you typically use a Subject or one of its variants like BehaviorSubject, ReplaySubject, or AsyncSubject. These act both as Observables and Observers, allowing you to manually control emissions. Here is a guide on how to do this:
Using a Subject
Subjects are multicast Observables. They allow you to not only broadcast values to multiple subscribers but also manually emit values.
Example with a Subject
import { Subject } from 'rxjs';
// Create a new Subject
const subject = new Subject();
// Subscribe to the Subject
subject.subscribe({
next: (v) => console.log(`observerA: ${v}`)
});
subject.subscribe({
next: (v) => console.log(`observerB: ${v}`)
});
// Manually emit values
subject.next(1);
subject.next(2);
// Output will be:
// observerA: 1
// observerB: 1
// observerA: 2
// observerB: 2
Using a BehaviorSubject
If you want the subject to have an initial value, you can use BehaviorSubject. It requires an initial value and emits the latest value to new subscribers.
Example with a BehaviorSubject
import { BehaviorSubject } from 'rxjs';
// Create a new BehaviorSubject with an initial value
const subject = new BehaviorSubject(0);
// Subscribe to the BehaviorSubject
subject.subscribe({
next: (v) => console.log(`observerA: ${v}`)
});
// Manually emit new values
subject.next(1);
subject.next(2);
// Subscribe to the BehaviorSubject after some values have been emitted
subject.subscribe({
next: (v) => console.log(`observerB: ${v}`)
});
// Output will be:
// observerA: 0
// observerA: 1
// observerA: 2
// observerB: 2
// observerA: 3
// observerB: 3
Using a ReplaySubject
ReplaySubject records multiple emissions and replays them to new subscribers.
import { ReplaySubject } from 'rxjs';
// Create a new ReplaySubject that buffers the last 2 values
const subject = new ReplaySubject(2);
subject.next(1);
subject.next(2);
// Subscribe to the ReplaySubject
subject.subscribe({
next: (v) => console.log(`observerA: ${v}`)
});
subject.next(3);
subject.next(4);
// Output will be:
// observerA: 1
// observerA: 2
// observerA: 3
// observerA: 4