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();
There are finite and infinite Observables as best described in this article.
are completed in a specific foreseeable time frame, e.g. a network request or your Observable.of()
call.
might never be completed, e.g. Observing click events.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With