movex-core-util
Version:
Movex Core Util is the library of utilities for Movex
40 lines • 1.22 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.Observable = void 0;
const ts_pubsy_1 = require("ts-pubsy");
const misc_1 = require("../misc");
class Observable {
constructor(_state) {
this._state = _state;
this.pubsy = new ts_pubsy_1.Pubsy();
}
get() {
return this._state;
}
onUpdate(fn) {
return this.pubsy.subscribe('onUpdate', fn);
}
update(nextStateGetter) {
this._state = Observable.getNextStateFrom(this._state, nextStateGetter);
// TODO: Should it only call onUpdate when there actually is an update??
// Or should I leave that to the implementation
this.pubsy.publish('onUpdate', this._state);
return this;
}
/**
* Ability to transform the state
*
* @param mapFn
* @returns
*/
map(mapFn) {
const $next = new Observable(mapFn(this.get()));
this.onUpdate((nextRootState) => {
$next.update(mapFn(nextRootState));
});
return $next;
}
}
exports.Observable = Observable;
Observable.getNextStateFrom = (prev, a) => (0, misc_1.isFunction)(a) ? a(prev) : a;
//# sourceMappingURL=Observable.js.map