RxJS. combineAll, switchAll, mergeAll, combineAll

https://twitter.com/NyaBlk/status/1282372506427555841

import { mergeAll, switchAll, concatAll, combineAll, map, delay } from 'rxjs/operators';
import { of } from 'rxjs';
import { ajax } from 'rxjs/ajax';

const pokemonId$ = of(1, 5, 6);

function getPokemonName(id: number) {
  return ajax.getJSON(`https://pokeapi.co/api/v2/pokemon/${id}`).pipe(
    map(({ name }) => name),
    delay(2000)
  );
}

// mergeAll will subscribe to all of the inner Observables concurrently: 
// all requests will be made in parallel
pokemonId$
  .pipe(
    map(id => getPokemonName(id)),
    mergeAll()
  )
  .subscribe(console.log);
// Output: (2s) bulbasaur, charmeleon, charizard

// concatAll subscribes to each inner Observable only after the previous one has completed:
// it will wait until each request is done, before making a new one
pokemonId$
  .pipe(
    map(id => getPokemonName(id)),
    concatAll()
  )
  .subscribe(console.log);
// Output: (2s) bulbasaur, (2s) charmeleon, (2s) charizard

// switchAll will subscribe to the most recently emitted inner Observable: 
// it will only emit the response from the most recent request
pokemonId$
  .pipe(
    map(id => getPokemonName(id)),
    switchAll()
  )
  .subscribe(console.log);
// Output: (2s) charizard

// combineAll will wait until it has every value, and then combines them into an array
pokemonId$
  .pipe(
    map(id => getPokemonName(id)),
    combineAll()
  )
  .subscribe(console.log);
// Output: (2s) [bulbasaur, charmeleon, charizard]

Stackblitz

Похожие записи

RxJS Pipeable Operators

Начиная с версии rxjs 5.5 операторы вместо цепочки вызовов применяются как параметры функции pipe.

Поисковый запрос с помощью RxJS

Показательная и востребованная задача. Получение набираемого запроса из поля ввода через полсекунды после того, как пользователь закончил ввод с показом лоадера.

RxJS. Delay from array

import { of, from } from 'rxjs'; 
import { map, concatMap, delay } from 'rxjs/operators';

from([2,4,6,8]).pipe(
  concatMap(item => of(item).pipe(delay(1000)))
).subscribe(console.log);