每 x 秒从 Observable 获取数据,使用开始和停止按钮

Maj*_*jiD 0 rxjs angular

我有一个Observablex秒调用一次。

和两个名为StartStop 的按钮来控制 observable。

我想在用户按下停止按钮时停止进程并取消订阅,并在按下开始后每x秒开始获取数据

到目前为止我有:

public subscription: Subscription;
public isLoading: boolean = false;
public isStopped: boolean = true;

// Start Getting Data
getData() {
    this.isStopped = false;
    this.isLoading = true;

    this.subscription = this.proxy.InternetUserRwaits(model).pipe(
        repeatWhen(completed => {
            return completed.pipe(
                tap(_ => this.isLoading = false),
                delay(this.interval * 1000),
                tap(_ => this.isLoading = this.isStopped ? false : true),
            );
        }),
    )
    .subscribe(
        result => {
            this.isLoading = false;
            // ... rest of code
        },
        error => console.error(error)
    );
}

// Stop Getting Data
stopGettingData() {
    this.subscription.unsubscribe();
    this.isStopped = true;
    this.isLoading = false;
}
Run Code Online (Sandbox Code Playgroud)

但它在第一站后不起作用

JB *_*zet 5

最简单的方法是从一个间隔 observable 开始,每次它发出时,订阅你的服务 observable 来获取数据:

this.subscription = interval(5000).pipe(
  tap(() => this.isLoading = true)
  switchMap(() => myService.loadData())
  tap(() => this.isLoading = false)
  finalize(() => this.isLoading = false)
).subscribe(data => this.result = data);
Run Code Online (Sandbox Code Playgroud)