Adding support for reading the last value.

This commit is contained in:
Fabian Stamm 2019-08-22 13:54:56 +02:00
parent edd37246fb
commit 564166a781
3 changed files with 28 additions and 7 deletions

8
package-lock.json generated
View File

@ -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
}
}

View File

@ -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
}
}

View File

@ -20,6 +20,7 @@ export type ObservableInterface<T> = {
};
const ClosedSymbol = Symbol("Observable Closed");
const LastValueSymbol = Symbol("Observable LastValue");
export default class Observable<T = any> {
private subscriber: ObserverCallback<T>[] = [];
@ -30,12 +31,22 @@ export default class Observable<T = any> {
// 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<T>) {
if (this[ClosedSymbol])
throw new Error("Observable is closed!");
@ -45,6 +56,10 @@ export default class Observable<T = any> {
this.subscriber.push(callback)
}
/**
* Unsubscribe specified callback. After that, it will be discarded.
* @param callback The callback originally subscribed
*/
unsubscribe(callback: ObserverCallback<T> | ObserverCallbackCollect<T>) {
if (this[ClosedSymbol])
return;
@ -59,6 +74,10 @@ export default class Observable<T = any> {
}
}
/**
* Subscribe for a collection of changes
* @param callback Callback called once a or some values are available.
*/
subscribeCollect(callback: ObserverCallbackCollect<T>) {
if (this[ClosedSymbol])
throw new Error("Observable is closed!");
@ -89,7 +108,9 @@ export default class Observable<T = any> {
*/
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) {