42

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

selanac82
  • 2,920
  • 4
  • 27
  • 37
  • 1
    Possible duplicate, answered [here](https://stackoverflow.com/questions/41070443/rxjava-how-to-stop-and-resume-a-hot-observable-interval) – udalmik Oct 26 '17 at 21:00

2 Answers2

48

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>
Nicholas Tower
  • 72,740
  • 7
  • 86
  • 98
45

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.

martin
  • 93,354
  • 25
  • 191
  • 226
  • 2
    `subscribe` leads to imperative reactive code, particularly when the intent is to `unsubscribe`. This is easier to construct at small scales, but harder to maintain at large scales. E.g. https://medium.com/@benlesh/rxjs-dont-unsubscribe-6753ed4fda87 recommends avoiding this. – ariels May 13 '18 at 13:51
  • 2
    I took the liberty of creating a [jsfiddle](https://jsfiddle.net/anied/ruzqty4k/8/) where you can see this solution in action. – Alexander Nied Sep 30 '19 at 14:29