Rxjs observed change interval

I have an observable that must complete an action every X seconds. The value of X changes dynamically. I had problems when I considered how to change this interval on the fly at runtime. From what I can understand, the big breakthrough in my thinking was that Observables cannot change after they are defined, so trying to redefine Observalbe with a new interval value does not seem to be the right way for this.

I tried to work with the code located at https://www.learnrxjs.io/operators/transformation/switchmap.html.

So far, I think that switchMapat least on the right track. Can anyone give me an example or point me to resources that can help me?

At least the world definitely needs more examples of RxJs!

+8
source share
2 answers

You can dynamically control the period Subjectwith switchMapand interval. Whenever an object radiates a value, this value can be used to indicate the period of the interval:

const t = Date.now();

let subject = new Rx.Subject();
subject
  .switchMap(period => Rx.Observable.interval(period))
  .do(() => console.log('some action at time T+' + (Date.now() - t)))
  .take(8)
  .subscribe();

subject.next(50);
setTimeout(() => subject.next(100), 200);
setTimeout(() => subject.next(200), 400);
<script src="https://unpkg.com/rxjs@5/bundles/Rx.min.js"></script>
Run codeHide result
+9
source

Adding a working example to help googlers

let startButton = document.getElementById('start');
let stopButton  = document.getElementById('stop');
let updateButton = document.getElementById('update');
let i1 = document.getElementById('i1');

const start$ = Rx.Observable.fromEvent(startButton, 'click');
const stop$ = Rx.Observable.fromEvent(stopButton, 'click');
const update$ = Rx.Observable.fromEvent(updateButton, 'click')

const period = () => (parseInt(i1.value));


Rx.Observable.merge(
    start$, 
    update$, 
  )
  .switchMap(() => {
    return Rx.Observable.interval(period()).takeUntil(stop$);
  })
  .subscribe(res => {
    console.log('here in the subscription:' + res);
  })
<script src="https://unpkg.com/rxjs@5/bundles/Rx.min.js"></script>
<body>
  <button id="start">Start</button>
  <button id="stop">Stop</button>
  <button id="update">Update</button>
  <input id="i1" value=100></input>
</body>
Run codeHide result
+7
source

Source: https://habr.com/ru/post/1668992/


All Articles