UNPKG

@creditkarma/consul-client

Version:

A client for Hashicorp Consul written in TypeScript

76 lines 1.95 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Observer = void 0; const Utils = require("./utils"); class Observer { constructor(updater, value) { this._listeners = []; this._errorListeners = []; this._value = value || null; this._previous = null; this._isActive = true; updater((err, newValue) => { if (err !== undefined) { return this.updateErrors(err); } else if (newValue !== undefined) { return this.update(newValue); } else { return false; } }); } static create(value) { return new Observer(() => { }, value); } destroy() { this._value = null; this._isActive = false; this._listeners = []; } previous() { return this._previous; } current() { return this._value; } onValue(cb) { if (this._isActive) { this._listeners.push(cb); if (this._value !== null) { setTimeout(() => { cb(this._value); }, 0); } } return this; } onError(cb) { if (this._isActive) { this._errorListeners.push(cb); } return this; } update(value) { if (this._isActive && !Utils.deepEqual(value, this._value)) { this._previous = this._value; this._value = value; this._listeners.forEach((next) => { next(value); }); } return this._isActive; } updateErrors(err) { if (this._isActive) { this._errorListeners.forEach((next) => { next(err); }); } return this._isActive; } } exports.Observer = Observer; //# sourceMappingURL=Observer.js.map