0

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.

HDJEMAI
  • 9,436
  • 46
  • 67
  • 93
Mister_L
  • 2,469
  • 6
  • 30
  • 64

3 Answers3

2

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.

Yevgeniy.Chernobrivets
  • 3,194
  • 2
  • 12
  • 14
  • When the component gets destroyed, the `async` pipe unsubscribes automatically to avoid * potential memory leaks. – Yerkon Apr 02 '18 at 04:20
1

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

Dionisis K
  • 614
  • 5
  • 17
0

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`

Nadhir Falta
  • 5,047
  • 2
  • 21
  • 43
  • Hm, it seems that even in the answer which you have provided there are multiple confronting recommendations - latest "official" recommendation is to unsubscribe manually (they provide example using takeUntil and unSubscriptino subject, this is one way to do it). But "original" answer says what you quoted... So confusing.... – Yevgeniy.Chernobrivets Apr 02 '18 at 05:16