@angular-extensions/model
Version:
Angular Model - Simple state management with minimalistic API, one way data flow, multiple model support and immutable data exposed as RxJS Observable.
70 lines (66 loc) • 2.24 kB
JavaScript
import * as i0 from '@angular/core';
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
import { map, shareReplay } from 'rxjs/operators';
class Model {
constructor(initialData, immutable, sharedSubscription, clone) {
this.immutable = immutable;
this.clone = clone;
this._data = new BehaviorSubject(initialData);
this.data$ = this._data.asObservable().pipe(map((data) => this.immutable
? clone
? clone(data)
: JSON.parse(JSON.stringify(data))
: data), sharedSubscription
? shareReplay({ bufferSize: 1, refCount: true })
: map((data) => data));
}
get() {
const data = this._data.getValue();
return this.immutable
? this.clone
? this.clone(data)
: JSON.parse(JSON.stringify(data))
: data;
}
set(data) {
if (this.immutable) {
const clone = this.clone
? this.clone(data)
: JSON.parse(JSON.stringify(data));
this._data.next(clone);
}
else {
this._data.next(data);
}
}
}
class ModelFactory {
create(initialData) {
return new Model(initialData, true, false);
}
createMutable(initialData) {
return new Model(initialData, false, false);
}
createMutableWithSharedSubscription(initialData) {
return new Model(initialData, false, true);
}
createWithCustomClone(initialData, clone) {
return new Model(initialData, true, false, clone);
}
createWithConfig(config) {
const { initialData, immutable, sharedSubscription, clone } = config;
return new Model(initialData, immutable, sharedSubscription, clone);
}
}
ModelFactory.ɵprov = i0.ɵɵdefineInjectable({ factory: function ModelFactory_Factory() { return new ModelFactory(); }, token: ModelFactory, providedIn: "root" });
ModelFactory.decorators = [
{ type: Injectable, args: [{
providedIn: 'root'
},] }
];
/**
* Generated bundle index. Do not edit.
*/
export { Model, ModelFactory };
//# sourceMappingURL=angular-extensions-model.js.map