What is the purpose of calling complete() on rxjs Subject?
As an example: Calling complete on takeUntil() notifier Observable. Why do we need to do that, and not just call next() and be done with it?
P.S. If it's just a convention, why is it so?
A subject in RxJS is a special hybrid that can act as both an observable and an observer at the same time. This way, data can be pushed into a subject, and the subject's subscribers will, in turn, receive that pushed data.
Observable can inform only one observer, while Subject can inform multiple observers. for each subscription observable output is diffrent but if you are expecting same output for in diffrent observer recommended to use Subject!
Subject adds them to its collection observers. Whenever there is a value in the stream it notifies all of its Observers. The Subject also implements the next , error & complete methods. Hence it can subscribe to another observable and receive values from it.
But rxjs offers different types of Subjects, namely: BehaviorSubject, ReplaySubject and AsyncSubject.
complete
is normally called on subjects in order to send the completed
event through the stream. This is done in order to trigger observers that wait for that notification. For example:
var subject = new BehaviorSubject<int>(2);
var subjectStream$ = subject.asObservable();
var finalize$ = subjectStream$.pipe(finalize(()=> console.log("Stream completed")));
var fork$ = forkJoin(subjectStream$,of(1));
....
finalize$.subscribe(value => console.log({value}));
//output: 2, notice that "Stream completed" is not logged.
fork$.subcribe(values => console.log({values});
// no output, as one of the inner forked streams never completes
Furthermore, is a security measure in order avoid mem. leaks, as calling complete on the source stream will remove the references to all the subscribed observers, allowing the garbage collector to eventually dispose any non unsubscribed Subscription
instance.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With