1

I have this code in my app:

  public requestList(): Observable<Record[]> {
    return this.http.get(this.requestUrl)
      .map((response: any) => this.currentList = response.json())
      .catch(this.setError);
  }

I wish this list was loaded only once from my backend. So I need to check if the currentList is fulled. If so, I must ignore the http.get() and manually return currentList contents to the subscriber, transparently as if he was getting it from the backend. How can I achieve that?

  public requestList(): Observable<Record[]> {
    if (this.currentList !== undefined) {
      // MAGIC HERE: returning content that's already in this.currentList HOW?
    }
    return this.http.get(this.requestUrl)
      .map((response: any) => this.currentList = response.json())
      .catch(this.setError);
  }
NaN
  • 8,596
  • 20
  • 79
  • 153

1 Answers1

2

You can use the static of operator to create an observable that emits the provided value (or values in sequence if you pass multiple arguments) and then completes.

Example:

...
if (this.currentList !== undefined) {
  return Observable.of(this.currentList);
}
...

Here are some docs on it: reactivex.io, learn-rxjs

Also it may be more appropriate to use the do/tap operator to modify the state of something outside of the stream since you aren't really intending to return a different value from map.

Example:

...
return this.http.get(this.requestUrl)
  .do((response: any) => this.currentList = response.json())
...

Here are some docs on it: learn-rxjs

Edit:

Found another post which is similar that deals with avoiding duplicate in-flight requests but also addresses caching. So for some more discussion on the topic you may want to check it out: What is the correct way to share the result of an Angular Http network call in RxJs 5?

Community
  • 1
  • 1
bygrace
  • 5,868
  • 1
  • 31
  • 58