how to unsubscribe for an observable

前端 未结 2 1777
星月不相逢
星月不相逢 2021-01-17 04:03

I have an angular application where I am reading a file and processing it and this processing is part of observable. I have a service which returns the observable an (ngbus

相关标签:
2条回答
  • 2021-01-17 04:35

    You must unsubscribe from the subscription, not the observable:

    processItems() {
        const ngbusy = this.myservice.observable.subscribe(items => {
            // perform some business logic 
    
    
            // unsubscribe at some point...
            ngbusy.unsubscribe();
        });
    
        // this will unsubscribe immediately...
        ngbusy.unsubscribe();
    
    }
    
    0 讨论(0)
  • 2021-01-17 04:53

    This is a good approach using takeuntil and ngUnsubscribe

    private ngUnsubscribe: Subject = new Subject();
    
    ngOnInit() {
      this.myThingService
        .getThings()
        .takeUntil(this.ngUnsubscribe)
        .subscribe((things) => console.log(things));
      /* if using lettable operators in rxjs ^5.5.0
          this.myThingService.getThings()
              .pipe(takeUntil(this.ngUnsubscribe))
              .subscribe(things => console.log(things));
          */
      this.myThingService
        .getOtherThings()
        .takeUntil(this.ngUnsubscribe)
        .subscribe((things) => console.log(things));
    }
    ngOnDestroy() {
      this.ngUnsubscribe.next();
      this.ngUnsubscribe.complete();
    }
    
    0 讨论(0)
提交回复
热议问题