Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 627
selanac82 Avatar asked Oct 26 '17 20:10

selanac82


People also ask

How do I stop RXJS interval?

Just unsubscribe: import { interval } from 'rxjs'; const subscription = interval(1000) .

How do I stop Observable timer?

call unsubscribe() on the Subscription object returned from the subscribe() call . use an operator.

What is Observable interval?

interval returns an Observable that emits an infinite sequence of ascending integers, with a constant interval of time of your choosing between those emissions. The first emission is not sent immediately, but only after the first period has passed.


2 Answers

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

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>
like image 51
Nicholas Tower Avatar answered Sep 20 '22 09:09

Nicholas Tower


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.

Jul 2019: Updated for RxJS 6.

like image 26
martin Avatar answered Sep 20 '22 09:09

martin