[Rxjs] Build a basic application store with Subjects
with application build Store Rxjs Basic
2023-09-14 08:59:12 时间
Store.js
import { BehaviorSubject, Subject } from 'rxjs';
import { map, distinctUntilKeyChanged, scan } from 'rxjs/operators';
export class ObservableStore {
private _store: BehaviorSubject<any>;
private _stateUpdate = new Subject();
constructor(initialState) {
this._store = new BehaviorSubject(initialState);
this._stateUpdate.pipe(
/*
* Accumulate state over time using scan.
* For this example we will just merge our current state
* with updated state and emit the result, however
* this could be any reducer / pattern you wish to follow.
*/
scan((current, updated) => {
return { ...current, ...updated }
}, initialState)
).subscribe(this._store);
}
/*
* Select a slice of state based on key.
*/
selectState(key: string) {
return this._store.pipe(
distinctUntilKeyChanged(key),
map(state => state[key])
);
}
/*
* Update state with new object to merge.
*/
updateState(newState: object) {
this._stateUpdate.next(newState);
}
/*
* Subscribe to any store state changes.
*/
stateChanges() {
return this._store.asObservable();
}
}
index.js
import { ObservableStore } from './store';
const store = new ObservableStore({
user: 'joe',
isAuthenticated: true
});
/*
* Select a slice of state from store.
*/
store.selectState('user').subscribe(console.log);
/*
* Update a property with new value.
*/
store.updateState({
user: 'bob'
});
store.updateState({
isAuthenticated: true
});
/*
* Selected state above (user) only emits when value has changed
* for the requested property.
*/
store.updateState({
isAuthenticated: false
});
相关文章
- ORA-24063: cannot downgrade QUEUE_TABLE that has queues with rule-based subscribers ORACLE 报错 故障修复 远程处理
- ORA-30372: fine grain access policy conflicts with materialized view ORACLE 报错 故障修复 远程处理
- ORA-38867: database not open: cannot create restore point with the specified timestamp ORACLE 报错 故障修复 远程处理
- ORA-46341: ALL STATEMENTS option cannot be supplied with BY SESSION clause ORACLE 报错 故障修复 远程处理
- ORA-53046: tag: string collides with existing tag: string in document: string ORACLE 报错 故障修复 远程处理
- ORA-19227: XPTY0007 – fn:data function is applied to a node (type (string)) whose type annotation denotes a complex type with non-mixed complex content. ORACLE 报错 故障修复 远程处理
- java.security.cert.CertPathValidatorException: Path does not chain with any of the trust anchors详解编程语言
- Exploring the Power of Linux with c sem: A Comprehensive Guide for Beginners(linuxcsem)
- Efficient Oracle Data Import: Simplifying Data Management with Bulk Loading(oracle批量入库)
- Master the Basics of Linux Network Management with Training Programs(linux网络管理实训)
- Streamlining HR Operations with Oracle: A Comprehensive Guide(oraclehr)
- Maximizing Security and Efficiency with LinuxBased PE Technology(linuxpe)
- Creating Dynamic Web Applications with ASP and MSSQL: A Comprehensive Guide(aspmssql)
- 分析学习Oracle深入理解使用With 分析(oracle使用with)