按顺序执行可观察的操作

时间:2019-09-11 16:56:26

标签: typescript rxjs

如何在打字稿中清楚地执行依赖于序列的可观察方法?

示例:

Init(){
    this.methodThatUseObservable();
    this.methodThatShouldExecuteAfter();
    this.anotherMethod();
    ... (continue)
}

在每种方法中,我都有一个可观察的方法并订阅。

methodThatUseObservable(){
   this.service1.get().subscribe(
      (value1) => {
         this.value1 = value1;
      }
   )
}
methodThatShouldExecuteAfter(){
   this.service2.get(this.value1).subscribe(  //depends on the first
      (value2) => {
         this.value2 = value2;
      }
   )
}
anotherMethod(){
   this.service3.get(this.value2).subscribe(  //depends on the second
      (value3) => {
         this.value3 = value3;
      }
   )
}
...(so on)

我可以做到的

Init(){
    this.methodThatUseObservable();
}

在每种方法中,其他依赖的方法:

methodThatUseObservable(){
   this.service1.get().subscribe(
      (value1) => {
         this.value1 = value1;
         this.methodThatShouldExecuteAfter();
      }
   )
}
methodThatShouldExecuteAfter(){
   this.service2.get(this.value1).subscribe(  //depends on the first
      (value2) => {
         this.value2 = value2;
         this.anotherMethod();
      }
   )
}
anotherMethod(){
   this.service3.get(this.value2).subscribe(  //depends on the second
      (value3) => {
         this.value3 = value3;
         ...(and so on)
      }
   )
}

但是我不太清楚,以这种方式我认为顺序不是很清楚。

也许解决方案返回一个promize并执行then方法?

    this.methodThatUseObservable().then(()=>{
       this.methodThatShouldExecuteAfter();
    }).then(()=>{
       this.anotherMethod();
    })

我不知道这种结构上的改变是否可能,请帮忙。

2 个答案:

答案 0 :(得分:2)

我不确定这是否是您的示例中的最佳实践,但是,我要做的是将每个方法包装在promise中,然后使用async / await以便以可读的方式链接它们。例如,在Angular中:

async ngOnInit(){
    try{
        await this.methodThatUseObservable();
        await this.method2();
        await this.method3();
        console.log("Done");
    }
    catch(e){
        //Handle errors
    }
}

methodThatUseObservable() : Promise<{}>{
    return new Promise(
        (resolve, reject) => {
            this.service1.get().subscribe(
                value1 => {
                    this.value1 = value1;
                    resolve();
                },
                error => {
                    reject('Error!');
                }
            )
        }
    )
}

...Same for method2, method3

答案 1 :(得分:1)

尝试一下:

import {concat, of} from "rxjs";

concat(
  of(() => this.methodThatUseObservable()),
  of(() => this.methodThatShouldExecuteAfter()),
  of(() => this.anotherMethod())
  ).subscribe(() => {}, error => {}, () => this.doYourStuff());