Skip to content

2. Observables

Andrei Antal edited this page Sep 25, 2021 · 1 revision

Challenge 9 - Building a cache with observables

private cache$: Observable<Movie[]>;
private reload$ = new BehaviorSubject(null);

...

reloadData() {
  this.reload$.next(null);
}
getMovies(searchTerm?: string): Observable<Movie[]> {
    if (!this.cache$ || searchTerm !== undefined) {
        // create the call and return
    }
    return this.cache$;
}
this.cache$ = merge(this.reload$, interval(REFRESH_INTERVAL)).pipe()
const REFRESH_INTERVAL = 10000;
this.cache$ = merge(this.reload$, interval(REFRESH_INTERVAL)).pipe(
  switchMap(() =>
    this.http.get<Movie[]>(
      `${this.moviesApiUrl}?q=${searchTerm ? searchTerm.trim() : ''}`
    )
  )
)
this.cache$ = merge(this.reload$, interval(REFRESH_INTERVAL)).pipe(
  switchMap(() =>
    this.http.get<Movie[]>(
      `${this.moviesApiUrl}?q=${searchTerm ? searchTerm.trim() : ''}`
    )
  ),
  shareReplay(1)
)
pipe(tap(() => this.reloadData()));
this.movies$ = this.searchField.valueChanges.pipe(
  debounceTime(300), 
  startWith(undefined),
  switchMap((searchTerm) => this.movieService.getMovies(searchTerm))
);

Diffs

Clone this wiki locally