We can use Subject as Observable and Observer:
// Subject should be only used to emit value for private // Using subject as an Observer const subject = new Subject(); subject.next(1); subject.next(2); subject.next(3); // Using subject as an Observable const source$ = subject.asObservable(); source$.subscribe(console.log);
AsyncSubject:
AsyncSubject only subscribe the latest value before subject complete.
const as = new AsyncSubject(); as.next(1); as.next(2); as.next(3); as.complete(); // it is necessary to complete it in order to get last value const source$ = as.asObservable(); source$.subscribe(console.log); // 3
If we don't call 'as.complete()', we won't get any value in the console.
Different from AsyncSubject, we have ReplySubject:
It doesn't need to call complete() in order to emit value. And it emit all the values from every beginning.
const rs = new ReplaySubject(); rs.next(1); rs.next(2); rs.next(3); const source$ = as.asObservable(); source$.subscribe(console.log); // 1,2,3