Search code examples
rxjsangular7rxjs6

update value in subscription


I have a service periodical api call that changes the url if this is the first time it's called.

It has a interval subscription for generating api call, I can't use a global variable because it's a service that can be invoqued without remove the injector.

getData(init: boolean): Observable<any> {

   const refreshInterval = 5000;
   const interval = observableInterval(refreshInterval).pipe(startWith(0)) 

  return interval.pipe(
    flatMap(() => this.http.get<any>(this.getUrl(init))), 
    map((data) => this.doWhateverWithData(data)),
  );

}

getUrl(init: boolean): string {

    return init ? url1 : url2;
}

My problem is init is not changing and so the url is either.

How can I solve it?

As I said, I can't use this.init because of my code.


Solution

  • I solve it. Just have to change the start with in the interval and check the value in flapMap

    getData(): Observable<any> {
    
       const refreshInterval = 5000;
       const interval = observableInterval(refreshInterval).pipe(startWith(-1)) 
    
       return interval.pipe(
          flatMap((index) => this.http.get<any>(this.getUrl(index))), 
          map((data) => this.doWhateverWithData(data)),
      );
    
    }
    
    getUrl(index: number): string {
    
       return (index === -1) ? url1 : url2;
    }