3

I have a initial data as: const menuItems = [{id: 1, active: false}, {id: 2, active: false}]

  public menuSubject$ = new BehaviorSubject<MenuItem[]>(menuItems);
  public menu$ = this.menuSubject$.asObservable();

I try to modify element where id: 1:

modify(id: number) {
   const menuItemsUpdated = this.menuSubject$.getValue().map((item) => {
      if(item.id === id) {
         return {...item, active: true};
      }
      return item;
   });

    this.menuSubject$.next(menuItemsUpdated);
}

I wonder is it properly way to do that using async getValue() and pushing this back?

  • it is fine. more rxjs way would be to create updates$ and merge it with the original stream to build the resulting value, but in your particular sutuation it woul just be a more comlicated way of solving the same problem – Andrei Feb 19 '21 at 14:52
  • Could you share this described aproach? –  Feb 19 '21 at 15:01
  • My code modifies all items of array. So something is wrong –  Feb 19 '21 at 15:05
  • it is not modifying all of the items. why did you think it does? – Andrei Feb 19 '21 at 15:24
  • Sorry it was, I had mistake in `_item` and `item`. –  Feb 19 '21 at 15:55
  • 1
    This is a good question and I asked pretty much the thing a few months back ["RXJS - BehaviorSubject: proper use of .value"](https://stackoverflow.com/questions/62262008/rxjs-behaviorsubject-proper-use-of-value). You may find some of the answers interesting. – BizzyBob Feb 19 '21 at 16:05

1 Answers1

-1

Seems ok. I would do the same thing .

Utukku
  • 1,315
  • 1
  • 10
  • 6
  • The template is blinking when whole object re-rendered. That is disandvantage –  Feb 19 '21 at 15:43