简体   繁体   English

如何在RxJS中停止Observable的间隔

[英]How to stop an interval on an Observable in RxJS

I have a specific situation where I'm using an RxJS interval, but at any given moment I may need to stop that interval. 我有一个特定的情况,我正在使用RxJS间隔,但在任何给定的时刻,我可能需要停止该间隔。 I assumed there was something easy like a cancel() or stop(). 我假设有一些像cancel()或stop()这样容易的东西。 Similar to clearTimeout. 与clearTimeout类似。 This is possible to stop an interval once it's going? 这可以在一段时间后停止一段时间吗? If not, what would be another approach. 如果没有,那将是另一种方法。

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

This is possible to stop an interval once it's going? 这可以在一段时间后停止一段时间吗?

You can use the .takeUntil operator to complete an observable when some other observable emits. 当其他一些observable发出时,您可以使用.takeUntil运算符来完成一个observable。 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: 您当然需要将其他可观察对象设置为以对您有用的方式发出值,但这是一个在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> 

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()是异步的,因此您也可以在subscribe的回调中调用unsubscribe()

Jul 2019: Updated for RxJS 6. 2019年7月:更新了RxJS 6。

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

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