Cancel a previouse event-triggered operation when a new event is triggered
Or in other words: Cancel a click-triggered REST-Call, when the user clicks again. This is a very neat recipe, that is used pretty often in our daily workflow, imagine you would have to achive the following usecase either with Promises or Callbacks:- Your requirement is to have a refresh-feature(e.g. auto-search), that is triggered whenever some input is made by a user
- BUT: The REST-Call for this can at times take longer then the next user-input
- In this case the previouse REST-call should be scrapped and only the latest call should be considered
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
// can be any observable or stream, e.g. some button-click-listener or maybe a timer let trigger$ = new Rx.Subject(); // whenever our trigger-stream emits data // we switch to the other stream, that will emit the async-operation-result (or "abort") // makeAsyncOperation will return an Observable (ENSURE, THAT THIS DOES NOT PROPAGATE AN ERROR) // we only want to take values from the rest-call until the next clickEvent happens let cancelAsyncOnNextTrigger$ = trigger$ .switchMap(() => makeAsyncOperation()) // the obligatory subscription to activate our stream cancelAsyncOnNextTrigger$.subscribe( result => console.log("Rest call result: " + result), error => console.error("Error: " + error.error) // whenever this is called, the stream starts itself again ); // this can be any operation, that returns an Observable function makeAsyncOperation(): Observable { return Rx.Observable.timer(2000); } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
let userInput$ = new Rx.Subject(); let refreshOnInput$ = userInput$ .switchMap(() => getDataFromBackend()) refreshOnInput$.subscribe( result => console.log("Rest call result: " + result), error => console.error("Error: " + error.error) ); function getDataFromBackend(): Observable { return Rx.Observable .fromPromise($http.get("http://...")) .catch(error => { // handle error... return Rx.Observable.empty(); }); } |
Leave a Reply