Search code examples
angulartypescriptrxjsrxjs6rxjs-observables

Reinitializing an Observable object


I would like to have the ability to reinitialize an Observable object. I don't know if "reinitialize" is the corrent term, but what I mean by that is that I would like to refresh the data

  1. without creating a new Observable object, and
  2. without creating new subscriptions (existing subscriptions to the existing Observable object should work seamlessly)
@Injectable({
  providedIn: 'root',
})
export class MyService {
  private url = 'http://mydummydomain.com/api/entries';
  private data$: Observable<any>;

  constructor(private http: HttpClient) {
    this.data$ = this.http.get(this.url).pipe(
      shareReplay(1)
    );
  }

  getData(): Observable<any> {
    return this.data$;
  }
  
  reloadData() {
    // TODO:
    // Refresh data from the url
    // Theoretically this should be a function with no input parameters and no return value
  }
}

Thanks


Solution

  • try this

    refresh$ = new Subject<void>();
    data$ = this.refresh$.pipe(startWith(null), switchMap(() => this.http.get(this.url)), shareReplay(1));
    
    
    reloadData() {
      refresh$.next();
    }