【问题标题】:RXJS wait for other ObservableRXJS 等待其他 Observable
【发布时间】:2019-02-05 14:41:40
【问题描述】:

我需要订阅一个结果,但要等待中间操作完成才能获得结果。诀窍是我“访问”我的结果来填充它:

// a service that gets a model
service.getModel(): Observable<MyModel>;

// I need to enrich my model before consuming it
service.getModel()
    .makeSureAllCodesAreFetched(data => visitModel(model))
    .subscribe(data => console.log("data is ready: ", data));

// a visitor that visits the model tree and enriches the leaves
// recursively visit the branches
visitModel(model: MyModel) {
    if (model.isLeaf) {
       // on condition, call a service to fetch additional data
       service.fetchCodes(model.codeKey).subscribe(codes => model.codes = codes);
    } else {
        model.properties.forEach(prop: MyModel => visit(prop));
    }
}

我尝试使用合并和 forkJoin() 没有成功。我只想确保在订阅我的数据之前完成对fetchCodes() 的所有调用,无论结果如何。

【问题讨论】:

  • 请编辑问题并添加您使用forkJoin() 尝试的内容 - 您可能已经接近可行的解决方案。

标签: rxjs rxjs5


【解决方案1】:

我找到了一个解决方案,但在我看来它不是最干净的。

// a service that gets a model
service.getModel(): Observable<MyModel>;

// I need to enrich my model before consuming it
service.getModel()
    .pipe(
        mergeMap(data => forkJoin(visitModel(model))))
    .subscribe(data => console.log("data is ready: ", data[0]));

// a visitor that visits the model tree and enriches the leaves
// recursively visit the branches
visitModel(model: MyModel, obs?: Observable<MyModel>[]): Observable<MyModel>[] {
    if (obs === undefined) {
        obs = [];
        obs.push(of(model)); // make sure the very first Observable is the root
    }
    if (model.isLeaf) {
       // on condition, call a service to fetch additional data
       // push Observable result in the array
       obs.push(service.fetchCodes(model.codeKey).map(codes => {
           model.codes = codes;
           return model;
       }));
    } else {
        model.properties.forEach(prop: MyModel => visit(prop, obs)); // recursive call
    }
    return obs;
}

我的访问者实际上会将所有对fetchCodes() 的调用附加到Observables 的数组中并返回它。这样forkJoin 将等待所有调用完成。诀窍(和肮脏的部分)是我必须确保第一个 Observable 实际上是我感兴趣的根元素。

【讨论】:

    猜你喜欢
    • 2021-12-03
    • 1970-01-01
    • 2021-11-16
    • 1970-01-01
    • 2021-08-28
    • 2017-09-04
    • 2020-09-27
    • 2021-11-04
    • 1970-01-01
    相关资源
    最近更新 更多