0

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 (ngbusy:subscription). I am subscribing to this observable in my component. The observable is assigned to an ngBusy which displays a spinner. Now the spinner keeps spinning even after subscribe is complete. I know we need to unsubscribe to the obervable. But when I unsubscri in the same method where we are subscribing, I don't even see the spinner displayed. Should we always use ngOndestroy to unsubscribe.

service.ts

const obsrv:Observable
obsrv= new Observable((observer) => {    
    // observable execution
    observer.next(this.items)
    observer.complete()
})

component.ts

processItems() {
    ngbusy  = this.myservice.observable.subscribe(items => {
        //perform some business logic 
    });
    this.myservice.observable.unsubscribe(); //not working here
}
Sébastien
  • 11,860
  • 11
  • 58
  • 78
user1015388
  • 1,283
  • 4
  • 25
  • 45

2 Answers2

1

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();

}
Sébastien
  • 11,860
  • 11
  • 58
  • 78
  • @Sebastian, thanks. I think I tried unsubscribing the subscription too. Let me try once more. Can that be done in the same method soon after subscribe code ends. – user1015388 Apr 28 '18 at 00:10
  • You should unsubscribe at a point where you don't need the subscription. If it is outside the method, assign the subscription to a class property instead of a variable. That way you can unsubscribe from anywhere in the class. – Sébastien Apr 28 '18 at 00:13
  • This isn't working for me. The spinner doens't go off. – user1015388 Apr 30 '18 at 13:10
0

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();
}
Mario Petrovic
  • 7,500
  • 14
  • 42
  • 62
Deeksha Bilochi
  • 106
  • 1
  • 8