Mister_L
Mister_L

Reputation: 2611

Angular 5: is unsubscribe needed from subject?

I'm looking at an example from the angular tour of heroes tutorial where a Subject is used to add debounce time on search.

However, the code does not contain any kind of unsubscribe on component destroy. Is unsubscribe not needed here? why? and if needed, what is the proper form to do this?

Thanks.

Upvotes: 0

Views: 2160

Answers (3)

Nadhir Falta
Nadhir Falta

Reputation: 5257

there are (2) kinds of Observables - finite value and infinite value.

http Observables produce finite (1) values and something like a DOM event listener Observables produce infinite values.

If you manually call subscribe (not using async pipe), then unsubscribe from infinite Observables.

Don't worry about finite ones, RxJs will take care of them.

Check this answer for me details:

Angular/RxJs When should I unsubscribe from `Subscription`

Upvotes: 0

Dionisis K
Dionisis K

Reputation: 644

Imagine that subscribing means you need some reference on memory (pointer) which tells to angular that there is a stream of events you have to check .
That's what subscribe does...
So when you finish with your stream you'll have a pointer pointing to something you can't use, since your component is destroyed and that is called a memory leak .
In this example it just passes the subject to the asynchronous pipe.There is no subscription

Upvotes: 1

Yevgeniy.Chernobrivets
Yevgeniy.Chernobrivets

Reputation: 3194

You do not need to unsubscribe in this case because you do not actually subscribe to it directly - there is no call to subscribe in component. It just passes resulting observable to async pipe which does all the clean up itself.

Upvotes: 2

Related Questions