Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RxJS the switch function

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.

like image 301
softshipper Avatar asked Oct 18 '22 02:10

softshipper


1 Answers

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.

like image 76
Brandon Avatar answered Oct 21 '22 04:10

Brandon