如何成对地缓冲可观察对象并由对执行它们?

时间:2017-10-18 10:34:14

标签: rxjs rxjs5

我有一个xhr请求正在获取一个数组,我可以像这样执行后续的xhr请求:

const Rx = require('rxjs/Rx');
const fetch = require('node-fetch');

const url = `url`;

// Get array of tables
const tables$ = Rx.Observable
  .from(fetch(url).then((r) => r.json()));

// Get array of columns
const columns$ = (table) => {
  return Rx.Observable
    .from(fetch(`${url}/${table.TableName}/columns`).then(r => r.json()));
};

tables$
  .mergeMap(tables => Rx.Observable.forkJoin(...tables.map(columns$)))    
  .subscribe(val => console.log(val));

我想在chuncks中执行列请求,以便不会立即将请求发送到服务器。

这个问题在某种程度上是相同的,但不完全是:Rxjs: Chunk and delay stream?

现在我尝试这样的事情:

tables$
  .mergeMap(tables => Rx.Observable.forkJoin(...tables.map(columns$)))
  .flatMap(e => e)
  .bufferCount(4)
  .executeTheChunksSerial(magic)
  .flatMap(e => e)
  .subscribe(val => console.log(val));

但我无法理解如何串联执行这些块...

1 个答案:

答案 0 :(得分:2)

您可以利用concurrency的{​​{1}}参数同时向服务器发送最多 x 请求:

mergeMap
const getTables = Promise.resolve([{ tableName: 'foo' },{ tableName: 'bar' },{ tableName: 'baz' }]);
const getColumns = (table) => Rx.Observable.of('a,b,c')
  .do(_ => console.log('getting columns for table: ' + table))
  .delay(250);
      
Rx.Observable.from(getTables)
  .mergeAll()
  .mergeMap(
    table => getColumns(table.tableName),
    (table, columns) => ({ table, columns }),
    2)
  .subscribe(console.log)