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?
I was apparently just a few minutes away from the answer. A working solution seems to be to create a
Subjectfor user updates.Merge that subject with the HTTP observable (that you force to only execute once). Then, on update, you put the new
uservalue into the subject. That gets you an initial HTTP request followed by cached responses.Any more elegant approaches would be highly appreciated. :)