[RxJS] mergeAll - mergeMap

const input$ = fromEvent(textInput, 'keyup');

input$.pipe(
  map(event => {
    const term = event.target.value;
    return ajax.getJSON(`https://api.github.com/users/${term}`) // return a nested observable
  }),
  debounceTime(200),  
).subscribe((obs) => {
  obs.subscribe(console.log) // you have to subscribe again
})

 

One way can solve the problem is mergeAll: it will help to subscribe nested observable

const input$ = fromEvent(textInput, 'keyup');

input$.pipe(
  map(event => {
    const term = event.target.value;
    return ajax.getJSON(`https://api.github.com/users/${term}`) // return a nested observable
  }),
  debounceTime(200),
  mergeAll(),
).subscribe(console.log)

 

It is so common map + mergeAll, so can use mergeMap():

const input$ = fromEvent(textInput, 'keyup');

input$.pipe(
  debounceTime(200),  
  mergeMap(event => {
    const term = event.target.value;
    return ajax.getJSON(`https://api.github.com/users/${term}`) // return a nested observable
  }),
).subscribe(console.log)

 

posted @ 2022-10-18 21:17  Zhentiw  阅读(43)  评论(0)    收藏  举报