Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I need to unsubscribe from timer(1000)?

Tags:

angular

rxjs

If I create a timer() with one execution like:

timer(1000).subscribe(() => console.log("some logging"));

do I need to unsubscribe?

The docs say:

If period is not specified, the output Observable emits only one value

so, as far as i learned about RxJS yet, I guess, that timer() might be completed after the execution. But I am not quite sure. There is not marble diagram, which shows an completed timer().

NOTE

I am not asking about how to unsubscribe; I need to know if a timer() without a given period completes and does not need to be unsubscribed.

like image 605
scipper Avatar asked Jun 21 '19 19:06

scipper


2 Answers

It will complete since you are not providing the second argument "period".

Here is the documentation http://reactivex.io/rxjs/class/es6/Observable.js~Observable.html#static-method-timer

Here is an example exposing the error and complete in the subscription https://stackblitz.com/edit/angular-rxjs-timer-test?file=index.ts

I hope that is helpful

like image 51
Jake Avatar answered Oct 02 '22 16:10

Jake


This is a good question on the bases of the timer() documentation, which is a bit confusing if you do not read it carefully and in full, at it is initially stating:

... that emits an infinite sequence of ascending integers,...

Regardless, the answer to the question is NO, you do not have to unsubscribe as demonstrated by the accepted answer.

I wanted to offer here a little trick, (if you are unsure, in hurry or get lazy or sloppy understanding your rsjx tools), but still want to make sure, your subscriptions unsubscribe, you could use:

yourObservable.pipe(take(1)).subscribe( . . . // your action(s) //

The piped take(1) will close the subscription for you.

like image 44
Felix Avatar answered Oct 02 '22 15:10

Felix