为什么嵌套订阅不好? [英] Why nested subscription is not good?

查看:42
本文介绍了为什么嵌套订阅不好?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道应该避免嵌套订阅并应该使用 rxjs 运算符,但是我发现的有关此问题的文章通常只是说嵌套订阅不好,而没有解释原因(除了说可能会导致问题").

I know that nested subscriptions should be avoided and rxjs operators should be used, but the articles I found about this issue usually just saying that nested subscriptions is bad without explaining why(besides saying 'may cause issues') .

我想知道是否有人可以帮助解决这个问题?谢谢.

I'm wondering if anyone can help on this one? Thank you.

推荐答案

很好,因为这是一个常见问题.

Good that you are asking since this is a common problem.

考虑类似的事情

service.cal1().subscribe(val => {
  service.call2(val).subscribe( res => {
    *does things*
  }
}

您正在触发的是一个新的订阅(以及一个新的执行管道),每个值都是由 call1() 的 Observable 发出的.这可能会给您留下数百个未处理的 Observable 和订阅,这些都暂时留在内存中.

What you are triggering is a new Subscription (and therefor a new executed pipe) for each an every value that get emited by the Observable of call1(). This can leave you with hundreds of unhandled Observables ans Subscriptions which all stay in memory for the time being.

您需要知道,当您多次 subscribe() 到 Observable 时,您的订阅者不会收听完全相同的来源,而是会触发您定义的 Observable 管道的新副本.

You need to know that when you subscribe() to a Observable multiple times, your subscribers won't listen to the exact same source, instead they all trigger a new copy of your defined Observable pipeline.

可观察文档

Observable 立即(同步)推送值 1、2、3 订阅时

Observable that pushes the values 1, 2, 3 immediately (synchronously) when subscribed

强调我的

Observable 本身什么都不做,而是开始它的整个旅程每当订阅时

The Observable does nothing on its own but starts its whole journey whenever subscribed

这就是为什么你会尝试使用诸如 switchMap() 之类的东西来更改为另一个调用,而不是保持原始订阅不变.

That is why you would try to use something like switchMap() to change to the other call instead of leaving the original subscription as is.

这篇关于为什么嵌套订阅不好?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆