创建后更改可观察的间隔/设置 [英] Change Interval/settings of observable after creation

查看:20
本文介绍了创建后更改可观察的间隔/设置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 RxJS 中,如何在创建后更改间隔设置?

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);

它说TypeError:observable.interval 不是sixage.js:10:14 的函数"

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

jsbin

编辑:

这是使用接受的答案后的最终产品.

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

推荐答案

interval 是在'class' Rx.Observable 上定义的,而不是在原型级别,即不是在 Rx.Observable 的每个实例上.所以 observable.interval 在 observable 实例上肯定会给你那个错误.

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.

如果你是interval的修改源,我只能想到用一个subject来推送你的修改.这样就可以了:

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; });

然后你用 intervalUpdateS.onNext(newValue);

尚未测试,但希望能按原样工作.

Haven't tested but hopefully should work as is.

关于主题:https://github.com/Reactive-Extensions/RxJS/blob/master/doc/gettingstarted/subjects.md

关于 flatMap :http://reactivex.io/documentation/operators/flatmap.html为什么我们需要使用 flatMap?

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

这篇关于创建后更改可观察的间隔/设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆