如何停止rxjs间隔/计时器

时间:2019-05-16 18:29:35

标签: angular rxjs intervals

我找到了两个可以启动/停止rxjs计时器或间隔的示例,但是我很难将计时器停止。

下面的HTML代码段:

仅供参考:第一次按autoPlay()将触发我的自动播放间隔。再次单击将关闭自动播放。

我的Angular (click)事件将很好地触发autoPlay(),我的this.toggleMe会按预期工作(每1秒钟将值翻转为true和false)。

<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>

但是,我正在尝试通过Subject清除间隔;即this.stopPlay$.next();。但这不会停止间隔。

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 ?
	);        
 }
 
}

很高兴知道我在做错什么。

我的一些参考文献:

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

*更新-最终版本*

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
        }
    }

2 个答案:

答案 0 :(得分:0)

您应该更改此设置:

const autoPlayInter = interval(1000);
autoPlayInter.subscribe(() => (this.toggleMe.checked = !this.toggleMe.checked));
autoPlayInter.pipe(takeUntil(this.stopPlay$));  

对此:

const autoPlayInter = interval(1000);
autoPlayInter
    .pipe(takeUntil(this.stopPlay$))
    .subscribe(() => (this.toggleMe.checked = !this.toggleMe.checked));

原因: takeUntil影响订户,而不影响源。

答案 1 :(得分:0)

回答更新的代码:

应更改为以下内容:

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();
    }
 }