Home > front end >  RxJS scan can only access last pushed partial data
RxJS scan can only access last pushed partial data

Time:12-15

I have a BehaviorSubject that I want to update by passing a Partial<Type> so I have this code. Then the scan handles the merge between new and old data.

personUpdates$ = new BehaviorSubject<Partial<Person>>({});

person$ = this.personUpdates$.pipe(
  scan((acc, curr) => ({ ...acc, ...curr }), {
    name: '',
    firstName: '',
    lastName: '',
  } as Person)
);

updatePerson = (person: Partial<Person>) => {
  this.personUpdates$.next(person);
}

But the problem I have is to access the data in certain places. For example if i subscribe and log person$ in my constructor I can see the whole object no issues. But if I try to access it in other places I only receive the last updated value.

constructor() {
  // Always have the full object
  this.person$.subscribe((x) => console.log(x));
}

checkValues = () => {
  // Only have the last Partial values
  this.person$.pipe(first()).subscribe((x) => console.log(x));
};

How can I make sure I always get the whole object?

I have reproduced the issue in a StackBlitz Sandbox

CodePudding user response:

person$ needs to save its calculations for late subscribers,

use shareReplay(1)

  personUpdates$ = new BehaviorSubject<Partial<Person>>({});

  person$ = this.personUpdates$.pipe(
    scan((acc, curr) => ({ ...acc, ...curr }), {
      name: '',
      firstName: '',
      lastName: '',
    } as Person),
    shareReplay(1)
  );
  • Related