Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Purpose of "completing" an rxjs Subject?

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?

like image 935
Viacheslav Guselnykov Avatar asked Sep 25 '18 18:09

Viacheslav Guselnykov


People also ask

What is the use of subject in RxJS?

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.

Why use subject instead of observable?

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!

Why do we use subject in angular?

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.

What kind of subject is RxJS?

But rxjs offers different types of Subjects, namely: BehaviorSubject, ReplaySubject and AsyncSubject.


1 Answers

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.

like image 184
Jota.Toledo Avatar answered Sep 18 '22 05:09

Jota.Toledo