How to stop an rxjs interval/timer

bob.mazzo

I found a couple of examples where one can start/stop an rxjs timer or interval, however I'm having trouble getting my timer to stop.

HTML snippet below:

FYI: Pressing autoPlay() the first time will fire my auto-play interval. Clicking again will turn OFF auto-play.

My Angular (click) event will trigger autoPlay() just fine, and my this.toggleMe works as expected (flips value between true and false every 1 second).

<mat-slide-toggle #toggleMe color="primary" [checked]="toggleMe"></mat-slide-toggle>
<div>
  <mat-icon svgIcon="auto-flipper" (click)="autoPlay()"></mat-icon>
</div>

<!-- example of the two panels that are shown/hidden based on slide-toggle above -->
<show-panel-one
  [hidden]="toggleMe.checked"
></show-panel-one>

<show-panel-two
  [hidden]="!toggleMe.checked"
></show-panel-two>

However, I'm trying to clear the interval via the Subject; namely, this.stopPlay$.next();. But it won't stop the interval .

import { Component, ... } from "@angular/core";

@Component({
    selector: "auto-play",
    templateUrl: "./auto-play.component.html",
})

export class MyTestComponent implements OnChanges, OnInit {

autoPlay = false;
stopPlay$: Subject<any> = new Subject();
@ViewChild("examToggle") examToggle: MatSlideToggle;

constructor() {}

autoPlay(): void {
	this.autoPlay = !this.autoPlay;
	if (!this.autoPlay) {
		this.stopPlay$.next();
	}
	const autoPlayInter = interval(1000);
	autoPlayInter.subscribe(() => {
		this.toggleMe.checked = !this.toggleMe.checked;
	});
	autoPlayInter.pipe(
		// map((_) => {}),
		takeUntil(this.stopPlay$),  // Shouldn't the .next() above trigger the timer stop ?
	);        
 }
 
}

It would be great to know what I'm doing wrong.

Some of my references:

How to stop rxjs timer Restart the timer on an rxjs interval

* UPDATE - FINAL VERSION *

autoSwitch(): void {
        this.autoPlay = !this.autoPlay;

        if (this.autoPlay) {
            this.autoPlayInter = timer(0, 2000)
                .pipe(
                    takeUntil(this.stopPlay$),
                    tap((_) => (this.toggleMe.checked = !this.toggleMe.checked)),
                )
                .subscribe();
        } else {

            this.stopPlay$.next(); // this stops the timer
        }
    }

Nitsan Avni

answering the updated code:

should change to something like the following:

autoPlay() {
    this.autoPlay = !this.autoPlay;

    if (this.autoPlay) {
        this.autoPlayInter = interval(2000);
        this.autoPlayInter
            .pipe(takeUntil(this.stopPlay$))
            .subscribe(() => {
                this.examToggle.checked = !this.examToggle.checked;
            });
    } else {
        this.stopPlay$.next();
    }
 }

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related