Created
August 24, 2018 09:03
-
-
Save shadowmint/cd9f65e284d6a398ff5704fd3acbe2c7 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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