Home > Back-end >  Auto-initialize BehaviorSubject to cache global data
Auto-initialize BehaviorSubject to cache global data

Time:03-17

Simplified use case:

  1. I have Angular app with multiple modules, most (not all) of the modules use a list of airports
  2. I want to create a global-cache.service.ts and cache the airport list in BehaviorSubject which will be exposed as Observable. I only want to initialize the BehaviorSubject (hit the DB) when user lands on component that subscribes to that Observable (vs initializing it in the service controller)

Here's the starting point, can't get it to work (see comment after this.getAirpotsFromDB() call) :

global-cache.service.ts

airports: BehaviorSubject<string[]> = new BehaviorSubject(null);
get airports$(): Observable<string[]> {
  if (this.airports.getValue() == null) {
    //get list from db, and initialize the subject
    this.getAirportsFromDB();
    //**PROBLEM:** how do I return `this.airports.asObservable()` after it's initialized with data from the call above or return it from inside the call?
  }
  else{
    //list initialized, emit from subject (don't hit db)
    return this.airports.asObservable();
  }
}

getAirportsFromDB() {
  this.http.get<string[]>('/api/airports').subscribe((_result) => {
    this.airports.next(_result);
  });
}

myComponent1.ts

//imports global-cache.service but never subscribes to airports$ (service has many other arrays that are used here)
//User lands here first, `getAirportsFromDB()` never gets called, user goes to myComponent2

myComponent2.ts

...
airports$: any = this.globalCacheService.airports$;
//subscribed in html `airports$ | async`
...
//user lands here, `getAirportsFromDB()` is called, `airports` BehaviorSubject is initialized
//user then goes to myComponent3

myComponent3.ts

...
airports$: any = this.globalCacheService.airports$;
//subscribed in html `airports$ | async`
...
//`airports` BehaviorSubject emits last value (initialized in Component2). `getAirportsFromDB()` does not get called again

CodePudding user response:

You can try something like below, just use tap operator and save the value of http request in the BehaviorSubject and return Observable from getAirportsFromDB

export class Service {

  airports: BehaviorSubject<string[]> = new BehaviorSubject(null);

  get airports$(): Observable<string[]> {
    return this.airports.getValue()
        ? this.airports.asObservable()
        : this.getAirportsFromDB();
  }

  getAirportsFromDB(): Observable<string[]> {
    return this.http.get<string[]>('/api/airports')
      .pipe(
        tap((_result) => this.airports.next(_result))
      )
  }
}

Minor update: The BehaviorSubject observable isn't getting returned on the first call so subsequent calls to the getter wouldn't update the view, so you can use the code above only in case, that you use it as the cache and don't want to receive any updates

CodePudding user response:

In get airports() you should always return the observable. If the DB API hasn't already been called then call getAirportsFromDB as you are currently doing

It's up to the components that subscribe to the returned observable to check the returned data and update their views based on this (that will be asynchronous)

Angular University site has some detailed examples of services that would also help

  • Related