diff --git a/package-lock.json b/package-lock.json index bb9f27e..903f149 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,13 +1,13 @@ { "name": "@hibas123/utils", - "version": "2.1.0", + "version": "2.1.1", "lockfileVersion": 1, "requires": true, "dependencies": { "typescript": { - "version": "3.4.5", - "resolved": "https://registry.npmjs.org/typescript/-/typescript-3.4.5.tgz", - "integrity": "sha512-YycBxUb49UUhdNMU5aJ7z5Ej2XGmaIBL0x34vZ82fn3hGvD+bgrMrVDpatgz2f7YxUMJxMkbWxJZeAvDxVe7Vw==", + "version": "3.5.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-3.5.3.tgz", + "integrity": "sha512-ACzBtm/PhXBDId6a6sDJfroT2pOWt/oOnk4/dElG5G33ZL776N3Y6/6bKZJBFpd+b05F3Ct9qDjMeJmRWtE2/g==", "dev": true } } diff --git a/package.json b/package.json index 0e8d8cb..40f0491 100644 --- a/package.json +++ b/package.json @@ -16,7 +16,7 @@ "type": "git" }, "devDependencies": { - "typescript": "^3.4.5" + "typescript": "^3.5.3" }, "files": [ "src/", @@ -25,4 +25,4 @@ "readme.md" ], "private": false -} \ No newline at end of file +} diff --git a/src/observable.ts b/src/observable.ts index 5f144eb..557b702 100755 --- a/src/observable.ts +++ b/src/observable.ts @@ -20,6 +20,7 @@ export type ObservableInterface = { }; const ClosedSymbol = Symbol("Observable Closed"); +const LastValueSymbol = Symbol("Observable LastValue"); export default class Observable { private subscriber: ObserverCallback[] = []; @@ -30,12 +31,22 @@ export default class Observable { // Use symbol to make sure this property cannot be changed from the outside private [ClosedSymbol] = false; + private [LastValueSymbol]: T | undefined = undefined; + + get lastValue() { + return this[LastValueSymbol]; + } + get closed() { return this[ClosedSymbol]; } constructor(private collect_intervall: number = 100) { } + /** + * Subscribe to changes + * @param callback Callback called once a value is available + */ subscribe(callback: ObserverCallback) { if (this[ClosedSymbol]) throw new Error("Observable is closed!"); @@ -45,6 +56,10 @@ export default class Observable { this.subscriber.push(callback) } + /** + * Unsubscribe specified callback. After that, it will be discarded. + * @param callback The callback originally subscribed + */ unsubscribe(callback: ObserverCallback | ObserverCallbackCollect) { if (this[ClosedSymbol]) return; @@ -59,6 +74,10 @@ export default class Observable { } } + /** + * Subscribe for a collection of changes + * @param callback Callback called once a or some values are available. + */ subscribeCollect(callback: ObserverCallbackCollect) { if (this[ClosedSymbol]) throw new Error("Observable is closed!"); @@ -89,7 +108,9 @@ export default class Observable { */ send(data: T) { if (this[ClosedSymbol]) - throw new Error("Observable is closed!") + throw new Error("Observable is closed!"); + + this[LastValueSymbol] = data; this.subscriber.forEach(e => e(data)); this.events.push(data); if (!this.timeout) {