Observable.ts 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. import { ISubscribable, IUnsubscribable, Observer } from './Subscribable';
  2. export abstract class Observable<S extends { [key: string ]: any }, T> implements ISubscribable<S> {
  3. state: S
  4. protected transport: T
  5. protected observers: Observer<S>[] = []
  6. protected initialState: S
  7. constructor (transport: T, initialState: S) {
  8. this.initialState = initialState;
  9. this.state = { ...initialState };
  10. this.transport = transport;
  11. }
  12. public subscribe (observer: Observer<S>): IUnsubscribable<S> {
  13. this.observers.push(observer);
  14. return this;
  15. }
  16. public unsubscribe (observerToRemove: Observer<S>) {
  17. this.observers = this.observers.filter((observer) => observerToRemove !== observer);
  18. }
  19. public dispatch () {
  20. this.observers.forEach((observer) => observer(this.state));
  21. }
  22. public setState (updatedState: Partial<S>) {
  23. if (typeof this.state === 'object') {
  24. this.state = Object.assign(this.state, updatedState);
  25. } else {
  26. this.state = updatedState as S;
  27. }
  28. this.dispatch();
  29. }
  30. public refreshState () {
  31. this.dispatch();
  32. }
  33. }