订阅 Rx.Observable from 字符串不处理值赋值

subscription to Rx.Observable from string not working on value assignment

本文关键字:处理 赋值 字符串 Rx Observable from 订阅      更新时间:2023-09-26

这是一个基本的rxjs问题,我找不到答案。 假设我使一个字符串可观察,然后在一段时间后我想为其分配一个新值。 似乎没有观察到新值,因为它没有被记录下来。 我知道 rx 正在工作,因为初始值被记录为一连串字符。 您能否解释一下我做错了什么,以及我需要修改哪些内容才能记录此新值? 在这里,我使用 setTimeout 函数来更新变量,但实际上它将是一个 ajax 请求,返回保存该值的 JSON 对象。

var observableId = "hwebd788ew98ew9";
var sourceAid = Rx.Observable.from(observableId);
var subscriptionAid = sourceAid.subscribe(
function (x) {
    console.log('changed!', x);
},
function (err) {
    console.log('Error: ' + err);
},
function () {
    console.log('Completed');
});

setTimeout(function() {       
    observableId = "yrth5yu56uy56";
}, 2000);

下面是将数据推送到数组的示例

var first = [];
var s1 = new Rx.Subject();
s1.subscribe(first.push.bind(first));
s1.onNext('I');
s1.onNext('am');
setTimeout(function() {       
    s1.onNext('late');
    console.log('late',first);
}, 2000);
console.log('first'first);

如果你运行这个,你会得到

"first"
["I", "am"]
"late"
["I", "am", "late"]

我希望这有所帮助

首先,"初始值记录为字符级联"的原因是Observable.from接受可迭代对象作为参数。因此,当你给它传递一个字符串时:它被视为一个数组,每个字符都成为一个迭代器,其结果是每个字符一次记录一个。

创建可观察量的最简单方法

  1. 具有初始值。
  2. 随着时间的推移,可以传递更多值

是使用行为主体:

var stream = new Rx.BehaviorSubject('test0');
stream.subscribe(hash => console.log(hash));
var testCount = 0;
setInterval(() => stream.next(`test${++testCount}`), 500);
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.4.3/Rx.min.js"></script>

如果你想把这个可观察量传递给另一个类或函数,并且不希望它们能够在你的 BehaviorSubject 上调用next,你可以使用 asObservable 方法将它们传递给一个可观察量:

return stream.asObservable();

现在你可以不断更新你的行为主体,消费者将只能订阅事件,而不能创建新事件。

您需要执行Observable.next()将数据推送到所有订阅的方法。

让我解释一下你的问题

//this is a normal variable. updating anything will not effect observable
var observableId = "hwebd788ew98ew9";
//sourceAid will be an observable and the intitial value will be observableId
var sourceAid = Rx.Observable.from(observableId);
// you are subscribing the value which is good.
var subscriptionAid = sourceAid.subscribe(
function (x) {
    console.log('changed!', x);
},
function (err) {
    console.log('Error: ' + err);
},
function () {
    console.log('Completed');
});
// here youa re changing observableId which is normal javascript veriable and it has nothing to do with observable
setTimeout(function() {       
    observableId = "yrth5yu56uy56";
}, 2000);
// you need to eimt/change/add value to 'sourceAid' as it is subscribed and responsible to notify all methods subscribing it for updates.
//this will update
sourceAid.next("yrth5yu56uy56")