Search code examples
angularreduxrxjsngrxflux

Is there a name to this common state manegement pattern with rxjs? Does it have limitations?


In Angular applications, we typically do something like this to manage shared states:

import { BehaviorSubject } from 'rxjs';

interface User {
  id: number;
}

class UserService {
  private _users$ = new BehaviorSubject([]);

  users$ = this._users$.asObservable();

  deleteUser(user: User) {
    const users = this._users$.getValue();
    this._users$.next(users.filter(user => user.id !== user.id));
  }


  addUser(user: User) {
    const users = this._users$.getValue();
    this._users$.next([...users, user]);
  }


  updateUser(updatedUser: User) {
    const users = this._users$.getValue();
    this._users$.next(users.map(user => user.id === updatedUser.id ? updatedUser : user));
  }
}

This basically solves the same problem that, fundamentally, Flux-based and Redux-based patterns (like ngRx and redux itself) try to solve: how can we update shared state so that view components can act reactively to changes and will aways be able to show the true current state. But it is simpler than those patterns.

My question is: does this pattern have a known name? Do we have any advantage in using libraries like ngRx(or even redux in react) that would cover any limitation of this pattern?


Solution

  • That's a valid pattern, and that's why we also have introduced ngrx/component-store (https://ngrx.io/guide/component-store).

    The docs also provide pro/cons of both "ways": https://ngrx.io/guide/component-store/comparison