javascript - 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.
- 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...
- 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.
解决方案
第一种方法绝对没有错。如果你必须做 3 件事,那么没有办法避免最终写 3 行来做 3 件事。把它隐藏在额外的抽象后面只会把你的 3 个东西变成 3*N 个东西。
看看你的第一种方法和第二种方法的代码少了多少。在需要抽象之前不要抽象。在您有时但并非总是需要灵活地执行操作的情况下,您的第二种方法更可取。通过将操作拆分为单独的订阅,您可以更好地控制哪些操作何时运行。
推荐阅读
- c# - IdentityServer4 与外部提供者。使用 id_token 重定向到前端页面
- android - 从菜单中的链接创建新活动
- node.js - { MongoTimeoutError: 服务器选择在 30000 毫秒后超时
- kotlin - TornadoFX runAsyncWithProgress 具有可为空的返回类型
- c# - 有没有可以用多个符号表示为金字塔的求和函数
- angular - 在 NGINX 同一台服务器上运行 Node Express 服务器和 Angular 应用程序的问题
- python - 如果我使用嵌套的 for 循环,如何在 Python 中展平我的输出文本?
- javascript - 如何修复 div 纵横比?
- c# - 如何自定义 Datagrid 的列(并且只显示几个字段)
- android - 我一直在初始化(据我所知)对象上收到 NullPointerException