调用n次相同的可观察

时间:2019-01-20 12:47:19

标签: rxjs angular-httpclient

我有一个http get网络服务,我需要调用 n 次,每次都添加上次调用的返回值(第一次有默认值),我该怎么做? >

2 个答案:

答案 0 :(得分:0)

听起来您可以使用expand

const N = 4;

const source = of(1).pipe(
  expand((previous, index) => index === 4 ? EMPTY : of(previous * 2))
);

source.subscribe(console.log);

实时演示:https://stackblitz.com/edit/rxjs-fcpin2

答案 1 :(得分:0)

您可以从rxjs使用'expand'运算符。它将循环播放,直到为它提供了empty()。这是示例:

import { empty } from 'rxjs';
private service; <--- service that gives us the observable by some value
private initialValue: number = 5;
private counter: number = 0;
private source$: Observable<number> = this.service.getSourceWithValue(initialValue);

source$.pipe(
   expand(value => isCounterExceeded()
                   ? incrementCounterAndGetNextSourceObservableWithValue(value);
                   : empty()
   );
// if counter is not exceeded we will increment the counter and create another
// observable based on current value. If it is exceeded, we are stopping the loop by 
// returning the empty() observable

private incrementCounterAndGetNextSourceObservableWithValue(value: number): Observable<number> {
    this.counter++;
    return this.service.getSourceWithValue(value);
}

private isCounterExceeded() {
   return this.counter >= 4;
}