首页 > 解决方案 > How to properly run methods after subscription data come?

问题描述

I would like to find the best approach to running multiple methods, when some data arrives from Observable (e.g. HTTP request) and I need this data to call these methods.

I currently have 2 approaches, but both have some flaws in my opinion.

  1. Call methods inside subscription:
  getSomeData(): void {
    this.httpService.getData.subscribe(data => {
        this.firstMethod(data);
        this.secondMethod(data.partOfData);
        this.thirdMethod();
    }
  }

I don't like this approach, because there is many lines of code when you need to call many methods. Of course I could wrap these 3 methods inside another function and call only that one function, but is this a good solution? I'm not sure...

  1. Make request as Observable and subscribe to it seperately:
  getSomeData(): void {
    this.dataObservable = this.httpService.getData.pipe(share());
  }

  firstMethod() {
    dataObservable.subscribe(data => {...}
  }

  secondMethod() {
    dataObservable.subscribe(data => {...}
  }

  thirdMethod() {
    dataObservable.subscribe(data => {...}
  }

Here I'm not sure if subscribing multiple times to the same operator is a proper approach...

I would be very grateful for any recommendations / articles about this issue.

标签: javascriptangularrxjs

解决方案


第一种方法绝对没有错。如果你必须做 3 件事,那么没有办法避免最终写 3 行来做 3 件事。把它隐藏在额外的抽象后面只会把你的 3 个东西变成 3*N 个东西。

看看你的第一种方法和第二种方法的代码少了多少。在需要抽象之前不要抽象。在您有时但并非总是需要灵活地执行操作的情况下,您的第二种方法更可取。通过将操作拆分为单独的订阅,您可以更好地控制哪些操作何时运行。


推荐阅读