为什么toArray()会在后续订阅中复制元素?

时间:2017-11-28 21:10:15

标签: rxjs rxjs5 reactivex

我有以下代码,它包含3个对象列表(位置,机器,传感器)。然后根据父ID(位置具有机器,机器具有传感器)将它们映射到具有子项的对象 生成的可观察返回对象是Location(具有Machines列表,其中每个都有Sensors列表)。 它工作正常。但是我想获得一个Locations列表,但是当我在observable上使用toArray()时,返回的原始数组会与每个订阅重复。

function getLocations() {
  return [
    {id: 'loc1', name: 'Some location'},
    {id: 'loc2', name: 'Other location'},
    {id: 'loc3', name: 'New location'},
  ];
}
function getMachines() {
  return [
    {id: '1', name: 'Machine 1', location: 'loc1'},
    {id: '2', name: 'Machine 2', location: 'loc1'},
    {id: '3', name: 'Machine 3', location: 'loc2'},
    {id: '4', name: 'Machine 4', location: 'loc3'},
  ];
}
function getSensors() {
  return [
    {id: 's1', name: 'Sensor 1', machine: '1'},
    {id: 's2', name: 'Sensor 2', machine: '3'},
    {id: 's3', name: 'Sensor 3', machine: '1'},
    {id: 's5', name: 'Sensor 5', machine: '4'},
    {id: 's4', name: 'Sensor 4', machine: '2'},
  ];
}

const sensors$ = Rx.Observable.from(getSensors());
const machinesWithSensors$ = Rx.Observable.from(getMachines())
                                             .flatMap(machine => sensors$.filter(sensor => sensor.machine === machine.id).toArray().map(sensors => {
                                               return {...machine, sensors: sensors}
  }));

const allData$ = Rx.Observable.from(getLocations())
                                  .flatMap(location => machinesWithSensors$
                                    .filter(machine => machine.location === location.id)
                                    .toArray().map(machines => {
  return {...location, machines: machines};
}));
const allDataArr$ = allData$.toArray();
allData$.subscribe(s => console.log('allData1', s))
allData$.subscribe(s => console.log('allData2', s))
allData$.subscribe(s => console.log('allData3', s))
allDataArr$.subscribe(s => console.log('allDataArr1', s))
allDataArr$.subscribe(s => console.log('allDataArr2', s))
allDataArr$.subscribe(s => console.log('allDataArr3', s))

codepen上的示例: https://codepen.io/anon/pen/ooaBdj

为什么?我如何重置'每次订阅前的观察结果?

0 个答案:

没有答案