I am trying to use switchMap to cancel any previous http calls in Angular2. The code is basically
var run = ():Observable => {
var url = \'
The requests need to originate from the same underlying stream. Here's a factory function that will create an http service instance that should do what you want:
function httpService(url) {
// httpRequest$ stream that allows us to push new requests
const httpRequest$ = new Rx.Subject();
// httpResponse$ stream that allows clients of the httpService
// to handle our responses (fetch here can be replaced with whatever
// http library you're using).
const httpResponse$ = httpRequest$
.switchMap(() => fetch(url));
// Expose a single method get() that pushes a new
// request onto the httpRequest stream. Expose the
// httpResponse$ stream to handle responses.
return {
get: () => httpRequest$.next(),
httpResponse$
};
}
And now the client code can use this service like this:
const http = httpService('http://my.api.com/resource');
// Subscribe to any responses
http.httpResponse$.subscribe(resp => console.log(resp));
// Call http.get() a bunch of times: should only get one log!!
http.get();
http.get();
http.get();