asynchronous - How can I populate a collection asynchronically? -
i'm trying populate collection of supermarket adding products each supermarket, in asynchronous way.
the objective pass having this:
[{ name: 'supermarket x', products: [1, 2] }] to more this:
[{ name: 'supermarket x', products: [{ id: 1, name: 'cacao' }, { id: 2, name: 'milk' }] }] i got make base code cannot achieve populate first stream second 1 once it's completed.
any ideas?
i leave here jsbin structure make faster you
https://jsbin.com/nucutox/1/edit?js,console
thanks!
so, have getsupermarkets() function returns stream emits multiple supermarket objects , getproduct(id) function returns stream emits single product specified id , completes. , want map stream of supermarkets containing product ids stream of supermarkets containing "resolved" product objects. did right?
here's solution:
const supermarkets$ = getsupermarkets() .concatmap(supermarket => { const productstreams = supermarket.products .map(productid => getproduct(productid)); return rx.observable.combinelatest(productstreams) .map(products => object.assign({}, supermarket, { products })); }); supermarkets$.subscribe(x => console.log(x)); when new supermarket object arrives, first map array of product ids array of product observables, i.e. array<id> => array<observable<product>>. pass array combinelatest operator waits until each of observables produces value , emits array of values, i.e. array of product objects. produce new supermarket object products set array. want keep original supermarket object unchanged, that's why object.assign.
to make work had update implementation of getproduct(): use .of(product) operator instead of .from(product) product plain object want emit.
Comments
Post a Comment