RxJS:异步变异树

时间:2014-10-12 08:41:05

标签: javascript functional-programming reactive-programming rxjs

我有一系列对象需要通过向每个对象添加属性来异步修改:

[{ id: 1 }, { id: 2 }] => [{ id: 1, foo: 'bar' }, { id: 2, foo: 'bar' }]

同步相当于:

var xs = [{ id: 1 }, { id: 2 }];
// Warning: mutation!
xs.forEach(function (x) {
    x.foo = 'bar';
});

var newXs = xs;

但是,在我的情况下,我需要异步追加foo属性。我希望最终值是一系列添加了foo属性的对象。

我想出了以下代码来解决这个问题。在此示例中,我只是为每个对象添加一个值为bar的属性。

var xs = Rx.Observable.fromArray([{ id: 1 }, { id: 2 }]);
var propertyValues = xs
    // Warning: mutation!
    .flatMap(function (x) {
        return Rx.Observable.return('bar');
    });

var newXs =
    .zip(propertyValues, function (x, propertyValue) {
        // Append the property here
        x.foo = propertyValue;
        return x;
    })
    .toArray();

newXs.subscribe(function (y) { console.log(y); });

这是解决我的问题的最佳方法,还是Rx提供了一种更好的方法来异步变异序列中的对象?我正在寻找一个更清洁的解决方案,因为我有一个需要变异的深树,这段代码很快就变得非常谨慎了:

var xs = Rx.Observable.fromArray([{ id: 1, blocks: [ {} ] }, { id: 2, blocks: [ {} ] } ]);
var propertyValues = xs
    // Warning: mutation!
    .flatMap(function (x) {
        return Rx.Observable.fromArray(x.blocks)
            .flatMap(function (block) {
                var blockS = Rx.Observable.return(block);

                var propertyValues = blockS.flatMap(function (block) {
                    return Rx.Observable.return('bar');
                });

                return blockS.zip(propertyValues, function (block, propertyValue) {
                    block.foo = propertyValue;
                    return block;
                });
            })
            .toArray();
    });

xs
    .zip(propertyValues, function (x, propertyValue) {
        // Rewrite the property here
        x.blocks = propertyValue;
        return x;
    })
    .toArray()
    .subscribe(function (newXs) { console.log(newXs); });

也许我不应该首先进行这种突变?

1 个答案:

答案 0 :(得分:0)

您是否有理由需要创建两个单独的Observable:一个用于您正在更新的列表,另一个用于结果值?

如果您只是对原始列表执行.map(),您应该能够异步更新列表并订阅结果:

// This is the function that generates the new property value
function getBlocks(x) { ... }

const updatedList$ = Rx.Observable.fromArray(originalList)
    // What we're essentially doing here is scheduling work
    // to be completed for each item
    .map(x => Object.assign({}, x, { blocks: getBlocks(x)}))
    .toArray();

// Finally we can wait for our updatedList$ observable to emit
// the modified list
updatedList$.subscribe(list => console.log(list));

为了抽象这个功能,我创建了一个帮助函数,它将使用setTimeout显式安排每个项目的工作:

function asyncMap(xs, fn) {
    return Rx.Observable.fromArray(xs)
        .flatMap(x => {
            return new Rx.Observable.create(observer => {
                setTimeout(() => {
                    observer.onNext(fn(x));
                    observer.completed();
                }, 0);
            });
        })
        .toArray();
}

您可以使用此功能安排每个项目的工作:

function updateItem(x) {
    return Object.assign({}, x, { blocks: getBlocks(x) }
}

var updatedList$ = asyncMap(originalList, updateItem);
updateList$.subscribe(newList => console.log(newList));