我正在将数据批量加载到数据库中,并使用RxJS控制管道。
let event = 0;
parseStreamOfIndividualObjectsToInsert().pipe(
bufferCount(100), // batch the inserts in groups of 100
flatMap(batch => batchInsert(batch)
// I want to go on only when all batch inserts are complete
// performFurtherOperationOnlyOnce()
)
.subscribe(() => console.log('Hopefully will only log one event: ++event));
目前,观察者的下一个方法是在每个batchInsert()之后触发,但是我只希望在所有批处理插入都完成后触发一次。
我尝试了concat和flatMap等的多种组合,但仍然从bulkInserts()flatMap行中发出多个事件。理想情况下,仅在完成时才发出事件。
是否有可能仅在完成时发出?
谢谢
答案 0 :(得分:1)
您可以使用toArray
将可观察对象的流减少到一个列表中。
您需要确保parseStreamOfIndividualObjectsToInsert()
将最终完成。我用bufferCount
替换了take
,以强制完成流。
let event = 0;
parseStreamOfIndividualObjectsToInsert().pipe(
take(100), // Force the stream to complete after 100 emissions
// bufferCount(100),
flatMap(batch => batchInsert(batch),
toArray() # wait for Observable to complete
)
.subscribe(() => console.log('Hopefully will only log one event: ++event));
答案 1 :(得分:1)
async function test() {
const result = await Library.functionReturningAPromise()
const obj = new Example(result);
// do the rest of the logic
}
test().then(() => {
console.log("all done");
}).catch(err => {
console.log(err);
});
操作将执行您想要的操作。它将toArray
的整个流reduce
包含一个包含所有内容的事件:
const { bufferCount, flatMap, toArray } = require('rxjs/operators');
let event = 0;
parseStreamOfIndividualObjectsToInsert().pipe(
bufferCount(100), // batch the inserts in groups of 100
flatMap(batch => batchInsert(batch)
toArray()
)
.subscribe(() => console.log('Hopefully will only log one event: ++event));