Search code examples
javascriptangulartypescriptobservablebehaviorsubject

How do I modify a BehaviorSubject that contains an array without assigning the entire array?


I'm aware that if I want to add an item to an array BehaviorSubject I need to assign a copy of the entire array plus the new item using next().

However, I would like to push items into this array without having to assign an entire copy, I also have to perform other operations in this array, which seems complicated using BehaviorSubject.

Is there a way to accomplish what I want, or an alternative to BehaviorSubject that could help me? And whether there is or isn't an alternative, is there a good library that helps with this?

Example:

export class ArrayService {
  currentArray = new BehaviorSubject<[]>([]);

  addItem(){
    let newItem = 'newItem';
    currentArray.next([...this.currentArray.getValue(), newItem]);
  }
}


Solution

  • Make another array, push to it, then fire it.

    export class ArrayService {
      currentArray = [];
      currentArray$ = new BehaviorSubject<[]>(this.currentArray);
    
      addItem(){
        let newItem = 'newItem';
        this.currentArray.push(newItem);
        this.currentArray$.next(this.currentArray);
      }
    }