Skip to content

Instantly share code, notes, and snippets.

@shadowmint
Created August 24, 2018 09:03
Show Gist options
  • Save shadowmint/cd9f65e284d6a398ff5704fd3acbe2c7 to your computer and use it in GitHub Desktop.
Save shadowmint/cd9f65e284d6a398ff5704fd3acbe2c7 to your computer and use it in GitHub Desktop.
import {Subject} from 'rxjs';
export default class Model {
constructor(state) {
this.state = state;
this.loading = false;
this.error = null;
this._delta = new Subject(this);
this._subs = [];
}
/** Update the state of this model and publish related events */
async _update(operation) {
this.loading = true;
this._delta.next(this);
try {
await operation();
this.loading = false;
this.error = null;
}
catch (error) {
this.loading = false;
this.error = error;
}
}
/** Subscribe to changes on this model */
subscribe(onChange) {
this._delta.subscribe(onChange, async (error) => {
await this._update(() => {
throw error;
});
});
}
/** Dispose any pending operations */
dispose() {
this._subs.map(i => i.unsubscribe()());
this._subs = [];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment