Why is rxjs not canceling my promise?

旧时模样 提交于 2019-12-10 19:12:17

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/32190606/why-is-rxjs-not-canceling-my-promise

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!