Reputation: 141
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?
Upvotes: 13
Views: 11995
Reputation: 28434
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.
Upvotes: 14