2

In my angular app i would like to be able to cancel and http request that is make with Rxjs. The scenario:

isComponentAlive = true;

onSave() { 
    this.service.save(this.formValue).takeWhile(() => this.isComponentAlive).subscribe();
}

ngOnDestroy() { 
  this.isComponentAlive = false;
}

Than i have a cancel button which navigates to another route. I would like to cancel a pending http request, but this way is not working. I would like to do something more clear then calling unsubscribe to all my http request subscriptions

Claies
  • 22,124
  • 4
  • 53
  • 77
gog
  • 11,788
  • 23
  • 67
  • 129
  • `takeWhile` cannot be used to cancel a pending HTTP request, as the predicate it takes is called [when it receives a value](http://reactivex.io/rxjs/class/es6/Observable.js~Observable.html#instance-method-takeWhile) - i.e. when the HTTP request emits a response. – cartant Jun 19 '17 at 21:59

2 Answers2

4

In general there are two ways to do this.

  1. Manually unsubscribe

    onSave() { 
        this.sub = this.service.save(this.formValue).subscribe();
    }
    
    ngOnDestroy() { 
        this.sub.unsubscribe();
    }
    

    You can also create one instance of Subscription class and then just add handlers to it:

    private sub = new Subscription();
    
    onSave() { 
        this.sub.add(this.service.save(this.formValue).subscribe());
    }
    
    ngOnDestroy() { 
        this.sub.unsubscribe();
    }
    

    This way you don't need to have multiple subscriptions and manually call unsubscribe() on all of them.

  2. Use an instance of Subject to complete the source Observable

    private subject = new Subject();
    
    onSave() { 
        this.sub.add(this.service.save(this.formValue).takeUntil(subject).subscribe());
    }
    
    ngOnDestroy() { 
        this.subject.next();
    }
    

Btw, this is a very similar question to yours: RxJS: takeUntil() Angular component's ngOnDestroy()

martin
  • 93,354
  • 25
  • 191
  • 226
1

In order to cancel a subscription, you will need to keep a reference to it.

onSave() {
  this.saveSubscription = this.service.save(this.formValue).takeWhile(() => this.isComponentAlive).subscribe();
}

ngOnDestroy() {
  this.isComponentAlive = false;
  this.saveSubscription.unsubscribe();
}

And this should do the trick :)

atomrc
  • 2,543
  • 1
  • 16
  • 20