A common usecase is to discard certain rest-calls, that are not needed any more after certain user-inputs. The most prominent example would be, when a user uses some search-function, makes a request, makes another request and for some reason the first request arrives after the second request and the application displays the outdated data of the old request.
This is a perfect usecase for the switchMap
-operator.
searchInput$
.switchMap(() => makeRestCall());
In this case the stream will switch
to the rest-call, but only until new data in emitted on the searchInput$
, then the stream inside the switchMap
is discarded and a new rest-call is made. So a rest-result will only be considered if it finished before the next click.
And here is a fully fledged mocked example:
// some initial data-mocking
const Observable = Rx.Observable;
var counter = 1;
function mockDataFetch() {
return Observable.of(counter++)
.delay(500);
}
// the recipe
const searchInput$ = new Rx.Subject();
searchInput$
.do(searchInput => console.log("Searching for " + searchInput))
.switchMap(searchInput => mockDataFetch()
.map(result => ({result, searchInput}))
)
.do(data => console.log("Received result for " + data.searchInput + ": " + data.result))
.subscribe();
// simulating search inputs
searchInput$.next("google");
setTimeout(() => searchInput$.next("froogle"), 600);
setTimeout(() => searchInput$.next("doodle"), 800);
setTimeout(() => searchInput$.next("poodle"), 1000);
setTimeout(() => searchInput$.next("noodle"), 1600);
See live demo: https://jsbin.com/suzakahoro/1/edit?js,console