javascript / intermediate
Snippet
Sharing State with ReplaySubject
A ReplaySubject buffers a set number of values and 'replays' them to any new subscriber. This is ideal for caching data that is fetched once but needed by multiple components that might initialize at different times.
snippet.js
javascript
1
2
3
4
5
6
private cache = new ReplaySubject<string[]>(1);items$ = this.cache.asObservable();refresh() {this.http.get<string[]>('/items').subscribe(d => this.cache.next(d));}
angular
Breakdown
1
new ReplaySubject<string[]>(1)
Creates a subject that remembers exactly the last emitted value (buffer size 1).
2
this.cache.asObservable()
Exposes the data as a read-only stream to prevent external pollution of the subject.