【问题标题】:Unsubscribing Multiple Subscription from Different Functions从不同的功能取消订阅多个订阅
【发布时间】:2018-09-02 21:55:20
【问题描述】:

我有多个订阅功能。首先我将它放在 ngOnInit() 上,然后我有另一个名为 onSelectVillain() 的函数。所以我的问题是你可以只使用 this.subscription.unsubscribe()。还是我应该声明另一个订阅?

subscription: Subscription;

    ngOnInit() {
      this.subscription = this.heroService.getHeroes()
                       .subscribe(
                         heroes => this.heroes = heroes,
                         error =>  this.errorMessage = <any>error);
    }

    onSelectVillain(event) {
      this.subscription = this.villainService.getVillains()
                       .subscribe(
                         .....
    }

    ngOnDestroy(){
     this.subscription.unsubscribe()
    }

【问题讨论】:

  • 使用单独订阅是取消订阅的最佳方式。使用相同的变量为您提供最后订阅的订阅,而不是全部。因此,当您退订时,您需要参考所有这些信息来完成退订过程。

标签: angular rxjs subscriptions angular-http-interceptors angular-httpclient


【解决方案1】:

一旦subscription 值被替换,之前的订阅将丢失,它与任何其他值没有什么不同。

更简洁的方法是让不同的订阅具有有意义的名称 - heroesSubscriptionvillainsSubscription 等:

heroesSubscription: Subscription;
villainsSubscription: Subscription;

ngOnInit() {
  this.heroesSubscription = this.heroService.getHeroes().subscribe(...);
}

onSelectVillain(event) {
  // possibly needs to unsubscribe previous subscription
  if (this.villainsSubscription)
    this.villainsSubscription.unsubscribe()

  this.villainsSubscription = this.villainService.getVillains().subscribe(...)
}

ngOnDestroy(){
 this.heroesSubscription.unsubscribe()
 this.villainsSubscription.unsubscribe()
}

如果onSelectVillain可能被多次调用,则应取消之前的订阅。

代码没有显示手动订阅的好处。当可观察值仅在视图中使用时,可以使用 async 管道代替,因为它会自动完成所有订阅/取消订阅工作:

{{ heroService.getHeroes() | async }}

【讨论】:

  • @GraySingh 它会起作用,但通常不是这样。
  • 我的意思是另一个答案中建议的方法将起作用(取消订阅的附加主题)。是否需要取消订阅 observable 取决于 observable 本身。通常它需要。
  • 如果有帮助,我添加了示例。
  • 请检查您的 selectVillain。你叫 heroSubscription。应该是小人订阅
  • 不客气 请注意,如果订阅肯定是同步的、完全可观察的,例如Observable.of(1, 2),则无需处理订阅。但这在实际应用中很少发生。
【解决方案2】:

使用单独的订阅会更简洁 - 如果您使用相同的字段,您将永远不会(手动)取消订阅第一个订阅。此外,如果您不想用大量字段将组件弄乱,而这些字段仅包含订阅引用,我建议使用一种模式,该模式仅涉及使用一个主题,该主题在 ngOnDestroy 触发,并且在每次订阅之前您将使用 takeUntil。 所以你的代码可能看起来像这样:

private ngUnsubscribe = new Subject();

ngOnInit() {
  this.heroService.getHeroes()
                  .takeUntil(this.ngUnsubscribe)
                  .subscribe(
                     heroes => this.heroes = heroes,
                     error =>  this.errorMessage = <any>error);
}

onSelectVillain(event) {
  this.villainService.getVillains()
                     .takeUntil(this.ngUnsubscribe)
                     .subscribe(
                     .....
}

ngOnDestroy(){
    this.ngUnsubscribe.next();
    this.ngUnsubscribe.complete();
}

请参阅this 以获取更多参考。

请注意,订阅是“有限的”,因此在调用完整状态时,不一定需要手动取消订阅。 This 可能是一个很好的参考点。

【讨论】:

    猜你喜欢
    • 2012-05-26
    • 1970-01-01
    • 2023-03-14
    • 1970-01-01
    • 1970-01-01
    • 2015-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多