Search code examples
javascriptobservablerxjsreactivex

Change Interval/settings of observable after creation


In RxJS how would I change the interval setting after creation?

So far I have this, but it doesn't work

var observable = Rx.Observable.interval(500)
  .map(function (data) { return "Hello World " + data; });

observable.subscribe(console.log);

setTimeout(function () {
  observable.interval(3000);
}, 3000);

It says "TypeError: observable.interval is not a function at sixage.js:10:14"

jsbin

Edit:

This was the final product after using the accepted answer.

var intervalUpdateS = new Rx.Subject();
var observable = intervalUpdateS.startWith(500).flatMapLatest(function(intvl){
  return Rx.Observable.interval(intvl);
})
.map (function (data) { return "Hello World " + data; });

observable.subscribe(function (msg) {
  console.log(msg);
});

setTimeout(function () {
  intervalUpdateS.onNext(3000)
}, 3000);

jsbin


Solution

  • interval is defined on the 'class' Rx.Observable, not at the prototype level, i.e. not on every instance of Rx.Observable. So observable.interval on an observable instance will definitely give you that error.

    If you are the source of modification of the interval, I can only think of using a subject to push your modifications. This would work that way:

    var intervalUpdateS = new Rx.Subject();
    var observable = intervalUpdateS.flatMapLatest(function(intvl){
        return Rx.Observable.interval(intvl);
    })
    .map (function (data) { return "Hello World " + data; });
    

    Then you change the interval with intervalUpdateS.onNext(newValue);

    Haven't tested but hopefully should work as is.

    About subjects : https://github.com/Reactive-Extensions/RxJS/blob/master/doc/gettingstarted/subjects.md

    About flatMap : http://reactivex.io/documentation/operators/flatmap.html, and Why we need to use flatMap?