RxJS combineLatest:如何在一个值更改后获取发射?

aka*_*ppi 5 reactive-programming rxjs

我正在尝试学习RxJS库.我不太了解的一个案例在这个jsfiddle中描述(下面的代码也是如此).

var A= new Rx.Subject();
var B= new Rx.Subject();

A.onNext(0);    

// '.combineLatest' needs all the dependency Observables to get emitted, before its combined signal is emitted.
//
// How to have a combined signal emitted when any of the dependencies change (using earlier given values for the rest)?
//    
A.combineLatest( B, function (a,b) { return a+b; } )
 .subscribe( function (v) { console.log( "AB: "+ v ); } );

B.onNext("a");  
A.onNext(1);
Run Code Online (Sandbox Code Playgroud)

我想在"AB"日志中获得两次发射.一个是将B更改为"a"(A已经具有值0).另一个是从A变为1.

但是,只有订阅后发生的更改似乎很重要(即使A有值,因此可以计算组合结果).

我应该使用"热观察",或者其他方法.combineLatest吗?

我在实际代码中遇到的问题(比这个样本更大)是我需要在订阅之后进行单独的初始化,这会在两个不同的地方切换内容,而不是在前面清楚地显示初始值.

谢谢

pau*_*els 10

我觉得你误解了这项Subjects工作.Subjects 热的Observables.他们没有坚持价值观,所以如果他们收到onNext没有订户的价值,那么这个价值就会输给世界.

您正在寻找的是其中一个BehaviorSubjectReplaySubject两者保持过去的值,将其重新发布给新订阅者.在前一种情况下,您始终使用初始值构造它

//All subscribers will receive 0
var subject = new Rx.BehaviorSubject(0);

//All subscribers will receive 1
//Including all future subscribers
subject.onNext(1);
Run Code Online (Sandbox Code Playgroud)

在后者中,您可以为每个订阅设置要重播的值的数量

var subject = new Rx.ReplaySubject(1);
//All new subscribers will receive 0 until the subject receives its 
//next onNext call
subject.onNext(0);
Run Code Online (Sandbox Code Playgroud)

重写你的例子可能是:

var A= new Rx.BehaviorSubject(0);
var B= new Rx.Subject();    

// '.combineLatest' needs all the dependency Observables to get emitted, before its combined signal is emitted.
//
// How to have a combined signal emitted when any of the dependencies change (using earlier given values for the rest)?
//    
A.combineLatest( B, function (a,b) { return a+b; } )
 .subscribe( function (v) { console.log( "AB: "+ v ); } );

B.onNext("a");  
A.onNext(1);

//AB: 0a
//AB: 1a
Run Code Online (Sandbox Code Playgroud)

另一方面,当然要意识到这对你来说是全新的,在大多数情况下你不需要Subject直接使用,因为它通常意味着你试图将Rx与你已知范例的安全纠缠在一起.您应该问问自己,您的数据来自哪里?它是如何创建的?如果你对这些问题提出足够的要求,在你的事件链回到源头后,10次中有9次会发现它可能有一个Observable包装器.