UNPKG

softkave-js-utils

Version:

JavaScript & Typescript utility functions, types, and classes

83 lines 2.02 kB
export class RefreshableResource { constructor(props) { this.timeout = props.timeout; this.resource = props.resource; this.previous = null; this.refreshFn = props.refreshFn; this.onRefresh = props.onRefresh; this.onError = props.onError; this.intervalId = null; } start() { this.stop(); this.intervalId = setInterval(() => { this.__refresh(); }, this.timeout); return this; } stop() { if (this.intervalId) { clearInterval(this.intervalId); this.intervalId = null; } return this; } getValue() { return this.resource; } setValue(value) { this.previous = this.resource; this.resource = value; return this; } getPreviousValue() { return this.previous; } refresh() { this.stop(); return this.__refresh().finally(() => this.start()); } getRefreshTimeout() { return this.timeout; } setRefreshTimeout(timeout) { this.timeout = timeout; return this; } getRefreshFn() { return this.refreshFn; } setRefreshFn(refreshFn) { this.refreshFn = refreshFn; return this; } getOnRefresh() { return this.onRefresh; } setOnRefresh(onRefresh) { this.onRefresh = onRefresh; return this; } getOnError() { return this.onError; } setOnError(onError) { this.onError = onError; return this; } dispose() { this.stop(); } __refresh() { return this.refreshFn(this.resource) .then(newResource => { this.previous = this.resource; this.resource = newResource; this.onRefresh(this.resource, this.previous); }) .catch(error => { this.onError(error, this.resource); }); } } //# sourceMappingURL=RefreshableResource.js.map