【发布时间】:2017-10-27 00:42:00
【问题描述】:
我是 Rxjs 的新手,正在尝试在其中实现以下工作流程:
- 用户点击触发 HTTP 请求的菜单项
- 在响应到达之前,用户点击了第二个请求
-
第一个请求的订阅结束,第二个请求的订阅开始
// The code below sits inside the onClick event of my menu var callAction = function(someParameters) { return Rx.Observable.create(function(observer) { var subscribed = true; myHttpApi.someActionCall(someParameters).then( (data: any) => { if (subscribed) { // Send data to the client observer.next(data); // Immediately complete the sequence observer.complete(); } }).catch((err: any) => { if (subscribed) { // Inform the client that an error occurred. observer.error(ex); } } ); return function () { subscribed = false; } }); };
观察者进一步定义如下:
var observer = {
// onNext in RxJS 4
next: function (data) {
// Do what you need to do in the interface
},
// onError in RxJS 4
error: function (err) {
// Handle the error in the interface
},
// onComplete in RxJS 4
complete: function () {
//console.log("The asynchronous operation has completed.");
}
};
let subscription = callAction(somParameters).subscribe(observer);
我现在应该如何实现#3,从而结束对第一个请求的订阅并订阅新请求(在此示例中,为不同的菜单选项执行相同的代码块,因此基于不同的请求参数上)是否启动?
【问题讨论】:
-
查看示例 2:learnrxjs.io/operators/transformation/switchmap.html 并使用
Rx.Observable.from包装承诺,但请注意承诺不可取消。您可能要考虑改用RxJS AJAX observable。 -
您可能正在查看这样的排队模式stackoverflow.com/questions/46469442/…
-
@FanCheung 这里的模式不同——不是等待前一个完成,我希望前一个被中止,下一个成为我们订阅的那个。那怎么办?
-
@cartant 谢谢! switchmap 可能正是我所需要的——我会尝试的。
标签: rxjs