The documentation for RxJS
defines AsyncSubject
as follows:
The AsyncSubject is a variant where only the last value of the Observable execution is sent to its observers, and only when the execution completes.
I don't see where / why I would ever need to use this variant of subject. Can someone provide an explanation or a real-world example to illustrate why it exists and its advantages?
It looks like it could be useful for fetching and caching (one-shot) resources, since generally http.get will emit one response then complete.
From rxjs/spec/subjects/AsyncSubject-spec.ts
it('should emit the last value when complete', () => {
it('should emit the last value when subscribing after complete', () => {
it('should keep emitting the last value to subsequent subscriptions', () => {
Components that subscribe after the fetch will then pick up value, which is not the case for Subject
const subject = new Rx.Subject();
const asyncSubject = new Rx.AsyncSubject();
// Subscribe before
subject.subscribe(x => console.log('before complete - subject', x))
asyncSubject.subscribe(x => console.log('before complete - asyncSubject', x))
subject.next('value 1');
subject.complete();
subject.next('value 2');
asyncSubject.next('value 1');
asyncSubject.complete();
asyncSubject.next('value 2');
// Subscribe after
subject.subscribe(x => console.log('after complete - subject', x))
asyncSubject.subscribe(x => console.log('after complete - asyncSubject', x))
.as-console-wrapper { max-height: 100% ! important; top: 0 }
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.5.6/Rx.js"></script>