import { ReplaySubject } from 'rxjs';
const subject = new ReplaySubject(3, 500);
// 3: specify upto how much older values need to be stored.
// 500: amount of time upo which values should be stored
// Observer 1:
subject.subscribe(
{
next: (v) => console.log(`observerA: ${v}`),
}
);
subject.next(1);
// 1 will be logged and stored for A
subject.next(2);
// 2 will be logged and stored for A
subject.next(3);
// 3 will be logged and stored for A.
// after this new values will be stored and
// older values will be deleted
subject.next(4);
// Observer 2:
subject.subscribe(
{
next: (v) => console.log(`observerB: ${v}`),
}
);
// since now onwards B also subscribed subject
// hence previous buffered sized values [2,3,4] will also be
// logged for B and now onwards A,B both will subscribe the subject.
subject.next(5);
// Final Output:
// observerA: 1
// observerA: 2
// observerA: 3
// observerA: 4
// observerB: 2
// observerB: 3
// observerB: 4
// observerA: 5
// observerB: 5
Advantages
History and Caching: It maintains a buffer of previously emitted items, allowing late subscribers to receive historical data.
Multi-casting: Events are multicast to multiple subscribers, ensuring all of them receive the same event history.
Error Recovery: If one subscriber encounters an error, other subscribers can still receive events from the buffer.
Testing: Useful for simulating and verifying event streams in unit tests.
Time Travel: Can implement features like "time travel" by controlling buffer size or time window.
Consistency: Provides a consistent event stream across subscribers.
Complex use case
In this scenario, we aim to implement a dynamic drop-down with search functionality. The available options in the drop-down will depend on the user's search input. We'll explore two different methods to achieve this:
Method without ReplaySubject: In this approach, we will create a drop-down that includes a search input field. As the user types in the search input, the options displayed in the drop-down will be recalculated based on the entered search text. The filtering and updating of options will be handled directly using basic array manipulation and event handling.
Method with ReplaySubject: In contrast, the second approach utilises the power of ReplaySubject. We will still create a drop-down with a search input, but now the filtering process and option updates will be managed by a ReplaySubject. As the user interacts with the search input, the ReplaySubject will automatically handle the filtering and notify the drop-down to display the updated options. This method ensures better reactivity and a centralised data source for the filtered options.