'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 1:[1]

Your use case is a bit special, but if you really want to change the variable during stream subscription, you can use BehaviorSubject with withLatestFrom

init$=new BehaviorSubject('initialvalue');
getData(init: boolean): Observable<any> {

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

  return interval.pipe(
    withLatestFrom(init$),
    flatMap(res=>this.apiSql.get<any>(this.getUrl(res[1]))), 
    map((data) => this.doWhateverWithData(data)),
  );
}

you can always change init$ cached value by init$.next('new value')

Solution 2:[2]

In rxjs@6 you can use from as standalone function:

import { from } from 'rxjs';

See also migration to rxjs6 guide

https://github.com/ReactiveX/rxjs/blob/master/MIGRATION.md#import-paths

UPDATE

You need to switch to pipe syntax, make sure you import all operators used from rxjs/operators. For example:

import { map, filter, catchError, mergeMap } from 'rxjs/operators';

getDataListApi() {
    return this.http.get("/api/method")
        pipe(
           map((data: any[]) => {
             this.products = data; // here you can update your data as your requirement
             return true;
           }), catchError( error => {
             return throwError( 'Something went wrong!' )
           });
        )
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Fan Cheung
Solution 2 rofrol