Could someone please explain what the switch function in RxJS do?
I read the documentation but could not configure it out, how it works exactly.
If you have an observable stream of observable values, switch will flatten that nested observable into a single stream of observable values. It will feed you the values from the most recent inner stream produced by the outer stream.
It is probably easier with an example. Say that you have a textbox that controls data you receive from an AJAX query. Lets call this textbox the page number. Your goal is to display the results of the AJAX query for the page the user types into the text box. You can use switch
to construct an observable stream of that data:
function getPageData(pageNumber) {
// return the ajax query for this page
return $.ajax("/url?page=" + pageNumber));
}
var pageNumberValue = // some observable of the page number values coming from the text box
// this will be an observable of observables of the page data
var dataStreamOfStreams = pageNumberValue
.map(pageNumber => getPageData(pageNumber);
// everytime you change pages, this will "switch" to the new ajax call
// and return the results from that new call.
var dataStream = dataStreamOfStreams.switch();
I hope this helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With