我有不同数量的源流数据 - A,B,C。可以随时添加或删除源。
所以我创建了这样的源D的数组流来观察这个数组。
然后我想处理来自这个数组的内部数据(例如它们的值如何随时间变化)。
所以我转换他们的状态(toPairs)并在订阅D中聚合这些数据(见代码)。
const Rx = require("rxjs/Rx");
const Promise = require("bluebird");
const A = new Rx.BehaviorSubject("a1");
const B = new Rx.BehaviorSubject("b1");
const C = new Rx.BehaviorSubject("c1");
const DEFAULT_PAIRS = ['??', '??']; // [ <old value>, <new value> ]
const toPairs = ([, oldValue], newValue) => {
return [oldValue, newValue]
};
const A_ = A.asObservable().distinctUntilChanged().scan(toPairs, DEFAULT_PAIRS);
const B_ = B.asObservable().distinctUntilChanged().scan(toPairs, DEFAULT_PAIRS);
const C_ = C.asObservable().distinctUntilChanged().scan(toPairs, DEFAULT_PAIRS);
const D = new Rx.BehaviorSubject([A_, B_]);
D.asObservable()
.startWith([])
.flatMap(streams => {
return Rx.Observable.combineLatest(
...streams,
(...data) => data
)
})
.subscribe(v => {
console.log(v)
});
Promise
.delay(0)
.then(() => console.log('-- change A to new value --'))
.then(() => A.next("a2"))
.delay(0)
.then(() => console.log('-- change A to new value --'))
.then(() => A.next("a3"))
.delay(0)
.then(() => console.log('-- change A to the same value --'))
.then(() => A.next("a3"))
.delay(0)
.then(() => console.log('-- change D to the same array --'))
.then(() => D.next([A_, B_]))
.delay(0)
.then(() => console.log('-- change B to new value --'))
.then(() => B.next("b2"))
.delay(0)
.then(() => console.log('-- change C to new value --'))
.then(() => C.next("c2"))
.delay(0)
.then(() => console.log('-- change D to new array --'))
.then(() => D.next([A_, B_, C_]));
[ [ '??', 'a1' ], [ '??', 'b1' ] ]
-- change A to new value --
[ [ 'a1', 'a2' ], [ '??', 'b1' ] ]
-- change A to new value --
[ [ 'a2', 'a3' ], [ '??', 'b1' ] ]
-- change A to the same value --
-- change D to the same array --
[ [ '??', 'a3' ], [ '??', 'b1' ] ]
-- change B to new value --
[ [ 'a2', 'a3' ], [ 'b1', 'b2' ] ]
[ [ '??', 'a3' ], [ 'b1', 'b2' ] ]
-- change C to new value --
-- change D to new array --
[ [ '??', 'a3' ], [ '??', 'b2' ], [ '??', 'c2' ] ]
如您所见,每当我将任何数据传递给D时,我都会看到以前的值在输出中丢失。
还有一个奇怪的事情是&#34;将B改为新值&#34;部分:显示2个输出。第一行是正确的。然后它再次更新并打印出包含错误内容的意外行。
[ [ '??', 'a1' ], [ '??', 'b1' ] ]
-- change A to new value --
[ [ 'a1', 'a2' ], [ '??', 'b1' ] ]
-- change A to new value --
[ [ 'a2', 'a3' ], [ '??', 'b1' ] ]
-- change A to the same value --
-- change D to the same array --
[ [ 'a2', 'a3' ], [ '??', 'b1' ] ]
-- change B to new value --
[ [ 'a2', 'a3' ], [ 'b1', 'b2' ] ]
-- change C to new value --
-- change D to new array --
[ [ 'a2', 'a3' ], [ 'b1', 'b2' ], [ 'c1', 'c2' ] ]
如何修复此代码以打印出预期的行? 你能为这样的问题提出其他解决方案吗?