繁体   English   中英

如何停止rxjs间隔/计时器

[英]How to stop an rxjs interval/timer

我找到了一些例子,其中一个可以启动/停止rxjs计时器或间隔,但是我无法让我的计时器停止。

下面的HTML代码段:

仅供参考:第一次按autoPlay()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 ? ); } } 

知道自己做错了会很棒。

我的一些参考资料:

如何停止rxjs 计时器在rxjs间隔重启计时器

*更新 - 最终版本*

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

你应该改变这个:

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影响订户,而不是来源。

回答更新的代码:

应改为以下内容:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM