1

I am looking to cache the result of a specific Angular2 HTTP call (getting my user profile from the server), and I want that cache to remain valid until I update the profile.

This is the code I have, which does cache the value, but never updates it, even if the profile is changed.

readonly user$: Observable<User> = this.http
    .get(`${this.baseUrl}/me`)
    .map(r => r.json())
    .publishLast()
    .refCount();

updateProfile(user: User): Observable<any> {
    return this.http.put(`${this.baseUrl}/me`, user);
    // cause the existing user$-subscriptions to update with the user value
}

Preferably I want the profile to update the existing subscriptions with the user value passed to updateProfile. Can this be done nicely in an Rx-y way, or do I have to resort to using a Subject and updating that manually?

Vegard Larsen
  • 12,827
  • 14
  • 59
  • 102

1 Answers1

0

I was apparently just a few minutes away from the answer. A working solution seems to be to create a Subject for user updates.

Merge that subject with the HTTP observable (that you force to only execute once). Then, on update, you put the new user value into the subject. That gets you an initial HTTP request followed by cached responses.

private readonly userSubject = new Subject<User>();
readonly user$: Observable<User> = this.userSubject
    .merge(this.http
        .get(`${this.baseUrl}/me`)
        .map(r => r.json())
        .publishLast()
        .refCount()
    );

updateProfile(user: User): Observable<any> {
    return this.http.put(`${this.baseUrl}/me`, user)
        .map(r => r.json())
        .do(() => this.userSubject.next(user));
}

Any more elegant approaches would be highly appreciated. :)

Vegard Larsen
  • 12,827
  • 14
  • 59
  • 102