Eko
Eko

Reputation: 1557

Calling n times the same observable

I have a http get webservice which I need to call n times, adding the return of my last call each time (first time there is a default value) how can I do it ?

Upvotes: 1

Views: 602

Answers (2)

martin
martin

Reputation: 96891

This sounds like you could use expand:

const N = 4;

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

source.subscribe(console.log);

Live demo: https://stackblitz.com/edit/rxjs-fcpin2

Upvotes: 0

Pawel Kiszka
Pawel Kiszka

Reputation: 850

You can use 'expand' operator from rxjs. It will loop until it's supplied with empty() observable. Here is example:

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;
}

Upvotes: 1

Related Questions