UNPKG

@obsidize/rx-map

Version:

ES6 Map with rxjs extensions for change detection

58 lines (57 loc) 2.14 kB
import { BehaviorSubject, isObservable } from 'rxjs'; import { OneToManyRelationship } from './relationships/one-to-many-relationship'; import { RxEntityMap } from './maps/rx-entity-map'; import { Subsink } from './common/subsink'; /** * Base class for defining an app's storage data. * Use the define***() methods to stand up your core storage infrastructure. */ export class RxStore { constructor() { this.effectSubscriptions = new Subsink(); this.properties = new Set(); this.entityMaps = new Set(); this.oneToManyRelationships = new Set(); } onDestroyProperty(property) { property.error('store_property_destroyed'); property.unsubscribe(); } onDestroyEntityMap(entityMap) { entityMap.destroy(); } onDestroyOneToManyRelationship(relation) { relation.clear(); } defineProperty(startValue) { return this.registerProperty(new BehaviorSubject(startValue)); } registerProperty(property) { this.properties.add(property); return property; } defineEntity(selectKey) { return this.registerEntity(RxEntityMap.immutable(selectKey)); } registerEntity(entityMap) { this.entityMaps.add(entityMap); return entityMap; } registerEffect(effect) { if (isObservable(effect)) this.effectSubscriptions.add(effect.subscribe()); return effect; } defineEntityForeignKey(entityMap, selectForeignKey) { const entityFkRelationship = new OneToManyRelationship(entityMap, selectForeignKey); this.oneToManyRelationships.add(entityFkRelationship); this.registerEffect(entityFkRelationship.changes); return entityFkRelationship; } destroy() { this.effectSubscriptions.unsubscribe(); this.oneToManyRelationships.forEach((value) => this.onDestroyOneToManyRelationship(value)); this.entityMaps.forEach((value) => this.onDestroyEntityMap(value)); this.properties.forEach((value) => this.onDestroyProperty(value)); } }