Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I need to unsubscribe from Observable.of?

So, basically, new to rxjs and wanted to know,

Do I need to unsubscribe from Observable.of(data) or in newer rxjs versions, just plain of(data)?

i.e.

import {of} from 'rxjs';
const sub = of(data).subscribe();

is this necessary?

sub.unsubscribe();
like image 466
Mark Lopez Avatar asked Apr 28 '19 19:04

Mark Lopez


1 Answers

There are finite and infinite Observables as best described in this article.

Finite Observables

are completed in a specific foreseeable time frame, e.g. a network request or your Observable.of() call.

Infinite Observables

might never be completed, e.g. Observing click events.

Answer

While there is no real need to unsubscribe from finite Observables it's considered best practice to unsubscribe from every observable as you normally don't really know if it is really finite.

In order to not pile up multiple subscriptions in your code it is best to use advanced rxjs features, as shown in this article.

Why should I unsubscribe from an Observable?

An Observable is a stream of events. You can subscribe to this stream and get updates as the stream generates events with the subscribe function

.subscribe(
  onNext => {
    // Called if there was a normal event, e.g. data is emitted
  },
  onError => {
    // Called if there was an Error
  },
  onComplete => {
    // Called if the event stream ends OR an Error is encountered
  }
)

Every Subscription takes up space in memory and as long as the Observable does not complete the subscriptions won't terminate (but will still receive updates with the onNext()-Function, even if for example in angular the component gets destroyed). In order to prevent unexpected behavior and memory leaks you have to unsubscribe. Click to read more

like image 169
Daniel Habenicht Avatar answered Oct 11 '22 00:10

Daniel Habenicht