3

I want to know, when to unsubscribe on a Observable Subscription. And when there is no need to unsubscribe. It is kind of hard to understand the concept of the subscriptions.

I give you an example:

this.http
    .get(
        environment.baseUrl + "/user/init",
        this.storageService.getAuthHeader(),
    )
    .subscribe(
        (user: AppUser) => {
            console.log(user.username);
            this.currentUser = user;
        },
        (err: HttpErrorResponse) => {
            log(err);
            this.router.navigateByUrl("/login");
        },
    )
    .add((teardown: TeardownLogic) => {
        // this will get called always after the User is retrieved/ subscription is unsubscribed
        console.log("Unsubscribe automatically ?");
    });

in this call I get an Observable. But i get told that I need to manually "unsubscribe" every subscription, after a Component is destroyed. But no one can clearly explain why.

Also I always get the recommendation to use Pipes (which makes sense I think, when dealing with multiple asynchronous calls which are dependent on each other), but I wonder when to use it, because the whole pipe().take(1) ... call seems hacky or like a workaround "

I also read the documentation about Subscriptions RxJS which doesn't help me that much, but to know, that "teardownLogic" will always be applied after .unsubscribe()

I also read Difference between the methods .pipe() and .subscribe() on a RXJS observable

and

Angular/RxJs When should I unsubscribe from `Subscription`

which both don't really answer the "mechanics" of Subscription in RxJS / Angular

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
Luxusproblem
  • 1,913
  • 11
  • 23
  • 1
    Imagine you queried an API (which gets automatically unsubscribed when the result comes), it takes 10 seconds to responsd(for any reason). In between that, you navigated to a differnt component(destroying the present comp). After 10 seconds, the API errors out. Do you expect to get re-navigated to "/login"? – Ashish Ranjan Jan 20 '20 at 14:40
  • 2
    When the observable completes, or when it emits an error, all observers are automatically unsubscribed. So it's generally **not** necessary to unsubscribe from http observables, since they complete or error as soon as they get (or fail to get) the http response, unless of course you really don't want anymore to be notified of the response or error. The same generally goes for ActivatedRoute observables, form observables, which automatically complete when the component for which they are created is destroyed. – JB Nizet Jan 20 '20 at 14:42
  • 2
    You need to care about unsubscribing when the observable keeps emitting after the component is destroyed (like an interval observable, or a singleton service observable, or the router events observable). Not unsubscribing would mean that the observer, and thus the component, would be kept in memory and would keep being notified when the observable emits. – JB Nizet Jan 20 '20 at 14:44
  • @JBNizet Thank you for your answer. And when should I use **pipe().take(1)/takeUntil()** instead of a a regular subscribe ? Is it true that you don't have to "unsubscribe" when Piping or somehow store the Subscription object to unsubscribe it when **ngOnDestroy()** ? – Luxusproblem Jan 20 '20 at 15:13
  • It's not "instead of". You must always subscribe to consume the events emitted by an observable. Nothing will happen if you don' subscribe. You use take(1) (or first()) when you're only interested in the first event, and want to automatically unsubscribe after it has been emitted. You use takeUntil() when you want to be unsubscribed as soon as another observable emits. Regarding to unsubscribing in ngOnDestroy, read my previous comments. – JB Nizet Jan 20 '20 at 15:20
  • @JBNizet Ok. but, let's say you have a 10 second API call like @xyz suggested, and you want to retrieve only 1 element. So you use `pipe().take(1).subscribe(...)` , but then destroy the component or switch routes etc. after 3 seconds, do you need to "unsubscribe" manually, or will the piping, take care of that ? – Luxusproblem Jan 20 '20 at 15:38
  • 1
    No, you don't use take(1). That's useless, since the http observable will never emit more than 1 event. If you want the functions passed to subscribe to be executed even though the component is destroyed, then no, don't unsubscribe. If you don't want to execute them because the component has been destroyed, then yes, you must unsubscribe. – JB Nizet Jan 20 '20 at 15:41
  • @JBNizet thank you so much. Is there a documentation or a Guide how to use pipes and subscribes properly ? Or where do you got those information, so I don't have to perforate you with questions :) ? – Luxusproblem Jan 20 '20 at 15:45
  • https://rxjs-dev.firebaseapp.com/, https://www.learnrxjs.io/ – JB Nizet Jan 20 '20 at 15:50
  • 1
    Also: https://www.youtube.com/watch?v=Z76QlSpYcck – DeborahK Jan 20 '20 at 16:57

0 Answers0