Lfederzoni
Lfederzoni

Reputation: 23

Angular rxjs interval not subscribing

I have this piece of code:

interval(180000).pipe(takeUntil(this._unsub$)).subscribe(() => myFunc())

_unsub$ is a subject that is fired in ngOnDestroy method. My problem is that myFunc never get executed.

The same piece of code in another component works. I can't understand why.

timer(0, 180000).pipe(takeUntil(this._unsub$)).subscribe(() => myFunc())

works. My problem with timer is that sometimes calls the function even if I call

ngOnDestroy() {
   this._unsub$.next();
   this._unsub$.complete();
}

Any guess why this happens?

Upvotes: 0

Views: 1354

Answers (1)

Mrk Sef
Mrk Sef

Reputation: 8062

Both interval and timer are cold observables, and observables are lazy (unlike promises) so your timer isn't called until you subscribe and a new timer is created when you subscribe.

These two settups are the same:

const firstFunc = () => ...
const secondFunc = () => ...
const interval1$ = interval(180000).pipe(takeUntil(this._unsub$));
const interval2$ = interval(180000).pipe(takeUntil(this._unsub$));
interval1$.subscribe(firstFunc);
interval2$.subscribe(secondFunc);
const firstFunc = () => ...
const secondFunc = () => ...
const interval$ = interval(180000).pipe(takeUntil(this._unsub$));
interval$.subscribe(firstFunc);
interval$.subscribe(secondFunc);

So you have to consider when .subscribe is called. That's my best guess to explain the difference between very similar code in different components. If this._unsub$.next(); is called a moment before subscribing to your timer, then 180seconds later, the timer will still fire as it never received the _unsub$ signal.

Upvotes: 1

Related Questions