代码之家  ›  专栏  ›  技术社区  ›  user8743396

从不同功能取消订阅多个订阅

  •  1
  • user8743396  · 技术社区  · 7 年前

    我有多个有订阅的函数。首先我在ngOnInit()上有它,然后我有另一个名为onSelectVillain()的函数。所以我的问题是,你可以用这个。订阅取消订阅()。或者我应该声明另一个订阅?

    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()
        }
    
    2 回复  |  直到 7 年前
        1
  •  3
  •   Jay    7 年前

    使用单独的订阅会更干净,如果使用相同的字段,则永远不会(手动)取消第一次订阅。此外,如果您不想让组件中有太多字段,而这些字段只是保存订阅引用,我建议您使用一种模式,即只使用一个主题,该主题在Ngondestory触发,在每次订阅之前,您将使用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 这可能是一个很好的参考点。

        2
  •  1
  •   Estus Flask    7 年前

    一旦 subscription 值被替换,以前的订阅丢失,它与任何其他值都没有区别。

    一种更简洁的方法是让不同的订阅具有有意义的名称- heroesSubscription ,则, villainsSubscription 等:

    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 }}