Refresh / reload Hot Observable sequence using RxJS

I am working on Portal in Angular 2. When I log in, I make a request to the server to get a registered user profile. The method for extracting the user profile returns an observable, which is signed in 6 different places when the application loads.

If I used cold observable, this would result in 6 API calls to the server. So I switched to the hot observable by adding .publishLast (). RefCount ().

This led to a single data exchange request because the user profile is not updated on subsequent requests.

The problem starts here:

Now I have the "Edit Profile" function that updates the user profile via HTTP PUT, and as a result I would like to expire the previously signed Observables and somehow start the sequence again so that the API runs again and the subscriptions get updated data.

Is there any way to restart / restart the already signed observable sequence?

Here is the code for the user receiving the selection

fetch(){
    this.userObservable = Observable.fromPromise(this.getToken())
      .switchMap(token => {
        let headers = new Headers();
        headers.append('Authorization', `Bearer ${token}`);
        return this.http.get('/api/v1/admin/users/me?includes=role', {headers: headers})
      })
      .map((res: Response) => {
        let retVal: any = {
          data: new Deserializer({
            keyForAttribute: 'camelCase'
          }).deserialize(res.json())
        };
        this.user = retVal.data as MpUser;
        this.user.role = MpRoles[retVal.data.role[0].name];
        return this.user;
      })
      .publishLast()
      .refCount();
  }
+4
source share
1 answer

You can try to enter subjectto call a selection:

private fetchTrigger = new BehaviorSubject(null);

triggerFetch() {
  this.fetchTrigger.next();
}

fetch() {
  this.userObservable = Observable
    .combineLatest(
      Observable.fromPromise(this.getToken()),
      this.fetchTrigger
    )
    .switchMap(([token]) => {
      ...
    })
    ...
    .publishLast()
    .refCount();
}

Note that this example tokenretrieves only once. If you need to get a new token with every update:

private fetchTrigger = new BehaviorSubject(null);

triggerFetch() {
  this.fetchTrigger.next();
}

fetch() {
  this.userObservable = this.fetchTrigger
    .switchMap(() => Observable.fromPromise(this.getToken()))
    .switchMap(token => {
      ...
    })
    ...
    .publishLast()
    .refCount();
}
+4
source

Source: https://habr.com/ru/post/1666344/


All Articles