Angular 2 / RXJS - need some help batching requests

本小妞迷上赌 提交于 2019-12-06 11:12:53

This largely depends on what you're trying to achieve.

If you want to recursively call an Observable based on some previous Observable and you don't know how many times you're going to call it then use expand() operator.

For example this demo recursively creates 5 requests based on the response from the previous call (count property):

import { Observable } from 'rxjs/Observable';

function mockPostRequest(count) {
    return Observable.of(`{"count":${count},"data":"response"}`)
        .map(val => JSON.parse(val));
}

Observable.of({count: 0})
    .expand(response => {
        console.log('Response:', response.count);
        return response.count < 5 ? mockPostRequest(response.count + 1) : Observable.empty();
    })
    .subscribe(undefined, undefined, val => console.log('Completed'));

Prints to console:

Response: 0
Response: 1
Response: 2
Response: 3
Response: 4
Response: 5
Completed

See live demo: http://plnkr.co/edit/lKNdR8oeOuB2mrnR3ahQ?p=preview

Or if you just want to call a bunch of HTTP request in order one after another (concatMap() operator) or call all of them at once and consume them as they arrive (mergeMap() operator):

Observable.from([
    'https://httpbin.org/get?1',
    'https://httpbin.org/get?2',
    'https://httpbin.org/get?3',
  ])
  .concatMap(url => Observable.of(url))
  .subscribe(response => console.log(response));

Prints to console:

https://httpbin.org/get?1
https://httpbin.org/get?2
https://httpbin.org/get?3

See live demo: http://plnkr.co/edit/JwZ3rtkiSNB1cwX5gCA5?p=preview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!