Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is rxjs not canceling my promise?

I am using rxjs in my angular app. I don't always get the data back in the order I want when multiple REST calls are made.

Controller:

constructor() {
    rx.Observable.fromPromise(this.getExpenses(toDate, fromDate))).subscribe(res => {
            that.setExpenses(res);
    }); 
}

getExpenses(toDate, fromDate) {
    return this.expenseService.getExpenses(fromDate, toDate);   
}

updateDate() {
    rx.Observable.fromPromise(this.getExpenses(toDate, fromDate))).subscribe(res => {
            that.setExpenses(res);
    });     
}

Service:

getExpenses: function(fromDate, toDateloadExtendedData) {
    return Restangular.all('expenses').getList({fromDate: fromDate, toDate: toDate});
},

In my constructor, I want to get the results for the current year, but sometimes the user will update the date before the call in the constructor returns. I then have a race condition, because the user wants the updateDate info, not the constructor info. How do I get back the most recently requested data?

like image 313
jhamm Avatar asked Jan 21 '26 08:01

jhamm


1 Answers

Since you have done nothing to "link" the two sequences, how can RxJs ever know they are related?

You need to create a single stream, then you can use switch to observe the most recent request only:

constructor() {
    this._requests = new Rx.Subject();

    // listen to requests
    this._requests.switch().subscribe(res => this.setExpenses(res));

    // start the first request
    this._requests.onNext(this.getExpenses(toDate, fromDate));
}

updateDate() {
    // start a new request
    this._requests.onNext(this.getExpenses(toDate, fromDate));
}

Note that this won't actually cancel the previous requests. It will just ignore any results they produce. If you really want to cancel them, your expense service would need to provide an API for cancelling in-progress requests.

like image 189
Brandon Avatar answered Jan 23 '26 23:01

Brandon