Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RxJs difference between complete and unsubscribe in Observable?

Tags:

angular

rxjs

After complete event will unsubscribe Observable or not or any other difference?

like image 991
Sourabh Avatar asked Sep 06 '18 07:09

Sourabh


People also ask

What is the difference between unsubscribe and complete in RxJS?

Digging into the RxJS code it looks as though Subject.complete () will call complete on each of it's observers where as unsubscribe just removes all observers from the subject by setting observers to null. Interesting, thanks. From my experience with the API, the idea is that: you don't call the Observable, the Observable calls you.

How to unsubscribe from an observable in RxJS?

Normally for asynchronous logic, RxJS takes care of unsubscribing and immediately after an error or a complete notification your observable gets unsubscribed. For the knowledge, you can manually trigger unsubscribe with something like this: We have been given a thorough introduction to Observables, observers and subscriptions in RxJS.

What is a subject in RxJS?

Right now, let’s go to the second important concept of RxJS, which is the Subject. The Subject is another type of Observable, and it allows value to be consumed by many Observers, not like in the normal Observable just by one. This means that Subjects are multicast, and Observables are unicast.

When does observable subscribe call complete()?

When what is returned from Observable.subscribe is a Subscription and not a Subscriber. Subscribers don't call complete (). You can call complete () on a Subject or more typically it's called for you "indirectly" using operators such as take (), takeWhile (), ...


1 Answers

You complete an Observable, and unsubscribe a Subscription. These are two different methods on two different objects. You subscribe to an observable which returns a Subscription object.

If you want to stop listening to emits from the Observable you call subscription.unsubscribe().

If you want an Observable to be done with his task, you call observable.complete(). (this only exists on Subject and those who extend Subject). The complete method in itself will also unsubscribe any possible subscriptions.

When an Observable issues an OnError or OnComplete notification to its observers, this ends the subscription. Observers do not need to issue an Unsubscribe notification to end subscriptions that are ended by the Observable in this way.

like image 170
Poul Kruijt Avatar answered Oct 13 '22 11:10

Poul Kruijt