Skip to content

Instantly share code, notes, and snippets.

@alxpsr
Last active May 21, 2021 07:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alxpsr/f8bc13d6570e6bf28cd98c6dbf61586f to your computer and use it in GitHub Desktop.
Save alxpsr/f8bc13d6570e6bf28cd98c6dbf61586f to your computer and use it in GitHub Desktop.
switchMap vs flatMap/concatMap usage

Условия

  • Есть массив ссылок
const URLS = [
  'https://jsonplaceholder.typicode.com/todos/1',
  'https://jsonplaceholder.typicode.com/todos/2',
  'https://jsonplaceholder.typicode.com/todos/10',
  'https://jsonplaceholder.typicode.com/todos/11',
  'https://jsonplaceholder.typicode.com/todos/23',
]
  • Есть интерфейс ответа:
interface TodoResponse {
  userId: number;
  id: number;
  title: string;
  completed: boolean;
}
  • По каждой ссылке надо сделать гет-запрос (можно просто через fetch()) и получить ответ
  • Каждый ответ нужно сохранять в каком-то месте (аккумулировать)
  • В подписку должен упасть только результирующий массив ответов
  • Использовать RxJS

Ожидаемый результат

[
    {
        "userId": 1,
        "id": 1,
        "title": "delectus aut autem",
        "completed": false
    },
    {
        "userId": 1,
        "id": 2,
        "title": "quis ut nam facilis et officia qui",
        "completed": false
    },
    {
        "userId": 1,
        "id": 10,
        "title": "illo est ratione doloremque quia maiores aut",
        "completed": true
    },
    {
        "userId": 1,
        "id": 11,
        "title": "vero rerum temporibus dolor",
        "completed": true
    },
    {
        "userId": 2,
        "id": 23,
        "title": "et itaque necessitatibus maxime molestiae qui quas velit",
        "completed": false
    }
]

https://stackblitz.com/edit/rxjs-fzwzwo?file=index.ts

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment