【发布时间】:2021-04-13 12:40:51
【问题描述】:
我想在 observable 完成时执行代码。在我的代码中,我执行这个:
compact(): Observable<FileManifest> {
return this.loadIndex().pipe(
mergeMap((index) => index.walk()),
map((entry) => entry.manifest),
notUndefined(),
writeAllMessages(this.newPath, ProtoFileManifest),
finalize(async () => {
await Promise.all([
promises.rm(this.journalPath, { force: true }),
promises.rm(this.manifestPath, { force: true }),
]);
await promises.rename(this.newPath, this.manifestPath);
}),
);
}
问题在于 finalize 方法是为同步代码创建的。当我像上面那样执行异步代码时,代码将独立于订阅执行。
我希望在处理可观察资源时执行此操作,但我希望当我订阅时,我总是收到事件。
如何将异步代码放入 finalize 方法中?
谢谢 乌尔里希
【问题讨论】:
-
我建议将所有 Promise 转换为 observables。
mergeMap也接受承诺,因此您可以将在finalize中使用的承诺放入mergeMap。 -
在完成另一个 observable 后运行 observable 将是
concat*的工作。