Stream 如何有条件地合并单个可观察流中的对象?
流包含以下对象Stream 如何有条件地合并单个可观察流中的对象?,stream,reactive-programming,rxjs5,Stream,Reactive Programming,Rxjs5,流包含以下对象 const data = [ { type: 'gps', id: 1, val: 1 }, { type: 'gps', id: 2, val: 2 }, { type: 'speed', id: 2, val: 3 }, { type: 'gps', id: 3, val: 4 }, { type: 'speed', id: 4, val: 5 }, { type: 'gps', id: 4, val: 6 }, { type: '
const data = [
{ type: 'gps', id: 1, val: 1 },
{ type: 'gps', id: 2, val: 2 },
{ type: 'speed', id: 2, val: 3 },
{ type: 'gps', id: 3, val: 4 },
{ type: 'speed', id: 4, val: 5 },
{ type: 'gps', id: 4, val: 6 },
{ type: 'gps', id: 5, val: 7 }
]
如果ID相同,则合并对象。如果没有匹配的id,则忽略该对象:
[
[{type: 'gps', id:2, val:2}, { type: 'speed', id: 2, val: 3 }],
[{ type: 'speed', id: 4, val: 5 },{ type: 'gps', id: 4, val: 6 }]
]
我的想法是将同一类型的对象分组,最后得到两个新的流
Rx.Observable.from(data)
.groupBy((x) => x.type)
.flatMap((g) => ...)
....
然后,如果id
相等,则再次合并/压缩它们
我不确定如何在Rx中指定这一点,也不确定这是否是一种好方法。无需拆分流并再次合并。您可以使用
scan
收集对象,并筛选出不符合条件的对象
const数据=[
{type:'gps',id:1,val:1},
{type:'gps',id:2,val:2},
{type:'speed',id:2,val:3},
{type:'gps',id:3,val:4},
{type:'speed',id:4,val:5},
{type:'gps',id:4,val:6},
{type:'gps',id:5,val:7}
]
常量生成器$=Rx.可观察的源(数据)
发电机$
.扫描((acc,x)=>{
如果(R.包含(x.id,R.Pull('id',acc))){
加速推力(x);
}否则{
acc=[x]
}
返回acc
}, [])
.filter(x=>x.length>1)
.subscribe(console.log)