javascript 如何在 RxJS 中停止 Observable 的间隔

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46963486/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 07:04:02  来源:igfitidea点击:

How to stop an interval on an Observable in RxJS

javascriptrxjsobservablerxjs5

提问by selanac82

I have a specific situation where I'm using an RxJS interval, but at any given moment I may need to stop that interval. I assumed there was something easy like a cancel() or stop(). Similar to clearTimeout. This is possible to stop an interval once it's going? If not, what would be another approach.

我有一个使用 RxJS 间隔的特定情况,但在任何给定时刻我可能需要停止该间隔。我认为有一些简单的东西,比如取消()或停止()。类似于 clearTimeout。一旦它开始,这有可能停止间隔吗?如果没有,另一种方法是什么。

Basically I have a large array that I'm stepping through. But there are external things that could happen that make it necessary to stop that step through and continue on to a new task. I'm hoping it's something simple that I'm just missing in the docs. Thanks

基本上我有一个大数组,我正在逐步完成。但是,可能会发生一些外部事件,因此有必要停止该步骤并继续执行新任务。我希望这是我在文档中遗漏的一些简单的东西。谢谢

回答by Nicholas Tower

This is possible to stop an interval once it's going?

一旦它开始,这有可能停止间隔吗?

You can use the .takeUntiloperator to complete an observable when some other observable emits. You'll of course need to set that other observable up to emit values in a way that is useful to you, but here's an example that stops an interval after 5 seconds:

.takeUntil当其他一些 observable 发出时,您可以使用操作符来完成一个 observable。您当然需要将其他 observable 设置为以对您有用的方式发出值,但这是一个在 5 秒后停止间隔的示例:

Rx.Observable.interval(100)
  .takeUntil(Rx.Observable.timer(5000))
  .subscribe(val => console.log(val));
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.5.2/Rx.min.js"></script>

回答by martin

Just unsubscribe:

只需退订:

import { interval } from 'rxjs';

const subscription = interval(1000)
  .pipe(...)
  .subscribe();

...

subscription.unsubscribe();

Note that since interval()is asynchronous you can call unsubscribe()inside the subscribe's callback as well.

请注意,由于interval()是异步的,您也可以unsubscribe()subscribe的回调中调用。

Jul 2019: Updated for RxJS 6.

2019 年 7 月:针对 RxJS 6 更新。