sainture
2/25/2018 - 6:57 AM

switchMap() operator

// imagine user types in the search box and the value changes before even you have received response
// from the server, switchMap is useful in that case.. it will cancel the old request and 
// replace it with the new one automatically



ngOnInit() {
  
  // produces a number every one second
  const numbers$ = Observable.interval(1000);
  
  // create observable of letters
  const letters$ = Observable.of('a', 'b', 'c', 'd', 'e');
  
  letters$.switchMap(x => 
    numbers$
    .take(5)
    .map(i => i + x)
  ).subscribe(z => console.log(z));
 
}


// output - for letter stream, it takes the last letter only
// 0e
// 1e
// 2e
// 3e
// 4e