71 lines
1.7 KiB
JavaScript
71 lines
1.7 KiB
JavaScript
(function(factory) {
|
|
if (typeof define !== 'undefined' && define.amd) {
|
|
define([], factory);
|
|
} else if (typeof define !== 'undefined' && define.petal) {
|
|
define(['promise-stream'], [], factory);
|
|
} else if (typeof module !== 'undefined' && module.exports) {
|
|
module.exports = factory();
|
|
} else {
|
|
window.PromiseStream = factory();
|
|
}
|
|
})(function() {
|
|
class PromiseStream {
|
|
constructor() {
|
|
this._current = new Promise((resolve) => {
|
|
this._resolve = resolve;
|
|
});
|
|
this._next = this._current;
|
|
this._value = undefined;
|
|
}
|
|
|
|
get promise() {
|
|
/* waits for the _first_ update, or completes immediately */
|
|
return this._current;
|
|
}
|
|
|
|
get next_promise() {
|
|
/* waits for the _next_ update (which may be the first) */
|
|
return this._next;
|
|
}
|
|
|
|
get value() {
|
|
return this._value;
|
|
}
|
|
|
|
update(value) {
|
|
if (value !== undefined && value !== this._value) {
|
|
const resolve = this._resolve;
|
|
const current = this._next;
|
|
const next = new Promise((resolve) => {
|
|
this._resolve = resolve;
|
|
});
|
|
|
|
this._current = current;
|
|
this._next = next;
|
|
this._value = value;
|
|
|
|
resolve({ value, next });
|
|
}
|
|
}
|
|
|
|
once(cb) {
|
|
this.promise.then((v) => { cb(v.value); });
|
|
}
|
|
|
|
listen(cb) {
|
|
function renew(v) {
|
|
if (cb !== undefined) {
|
|
cb(v.value);
|
|
v.next.then(renew);
|
|
}
|
|
}
|
|
|
|
this.promise.then(renew);
|
|
|
|
return () => { cb = undefined; };
|
|
}
|
|
}
|
|
|
|
return PromiseStream;
|
|
});
|