Jon Sud
Jon Sud

Reputation: 11641

Should I unsubscribe after complete invoked in rxjs?

In rxjs, if the complete method is invoked should I also invoke unsubscribe?

For example I have a timer from rxjs and I set to 5 seconds.

After the subscribe function is invoked should I run also unsubscribe from the timer?

import { timer } from "rxjs";

const token = timer(5 * 1000).subscribe({
  next: () => {
    console.log("xxx");

    token.unsubscribe(); // <---- should I do it to to free memory?
  },
  complete: () => {
    console.log("aaa");
  }
});

Upvotes: 3

Views: 1023

Answers (2)

Mrk Sef
Mrk Sef

Reputation: 8022

The question:

if the complete method is invoked should I also invoke unsubscribe?

No. An observable can only complete or error once. A completed or errored observable is done. There's no need to unsubscribe.

Timer, as invoked above, will only emit once and then complete. Unless you want to cancel the timer, there's no need to unsubscribe. If you give the timer a second argument, then it changes to act more like interval. Then you must unsubscribe.

Generalized:

Any short-lived observable will complete on its own. This is the case with promises, HTTP calls, observables created with of or from(array). These generally don't need to be unsubscribed unless some business logic dictates otherwise.

Long-lived observables don't complete on their own and must be managed somehow. User interactions tend to have no defined end (Think DOM events like button clicks). intervals have no defined end as well.

How to unsubscribe

The best solutions will be those that use operators that handle subscription/unsubscription on your behalf. They require no extra cognitive load in the best circumstances and manage to contain/manage errors relatively well (less spooky action at a distance) in the more exotic circumstances.

Most higher-order operators do this (concat, merge, concatMap, switchMap, mergeMap, ect). Other operators like take, takeUntil, takeWhile, ect let you use a more declarative style to manage subscriptions.

Where possible, these are preferable as they're all less likely to cause strange errors or confusion within a team that is using them.

Upvotes: 4

Anton Marinenko
Anton Marinenko

Reputation: 2982

Of course you should unsubscribe, just check token in console log. It has props: closed: true, _subscriptions: null, isStopped: true.

Compare if not unsubscribe: closed: false isStopped: false _subscriptions: Array[1].

If you want the complete value, you have to complete your Subject, in that case - timer.

Upvotes: 0

Related Questions