I am new to Rxjs and am trying to implement the following workflow in it:
- User clicks on a menu item that triggers an HTTP request
- Before the response has arrived, the user clicks on a second request
The subscription to the first request is ended and a subscription to the second request is started
// 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; } }); };
The observer is further defined below:
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);
How do I now go about implementing #3, whereby the subscription to the first request is ended and a subscription to the new request (in this example, the same block of code is executed for different menu options and therefore different requests based on the parameters) is started?