使用RXJS的这种常见状态操纵模式有名字吗?它有局限性吗?
在Angular应用程序中,我们通常会执行类似的事情来管理共享状态:
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));
}
}
这基本上解决了从根本上,基于磁通和基于REDUX的模式(例如NGRX和Redux本身)尝试解决:我们如何更新共享状态。因此,该视图组件可以反应地对变化作用,并且可以表现出真正的当前状态。但这比这些模式更简单。
我的问题是:这种模式有已知名称吗?我们在使用诸如NGRX(甚至REDUX中的Redux)之类的库中是否有任何优势可以涵盖此模式的任何限制?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是一个有效的模式,这就是为什么我们还引入了ngrx/component-store( https:// ngrx。 IO/指南/组件商店)。
文档还提供两种“方法”的支持/缺点: https://ngrx.io/guide /组件商店/比较
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