Making publicAPI also available on Observable class

This commit is contained in:
Fabian 2019-08-13 17:34:38 +02:00
parent d1fdb789c1
commit edd37246fb
2 changed files with 37 additions and 31 deletions

View File

@ -1,6 +1,6 @@
{
"name": "@hibas123/utils",
"version": "2.1.0",
"version": "2.1.1",
"description": "Different Utilities, that are not worth own packages",
"main": "lib/index.js",
"types": "lib/index.d.ts",
@ -25,4 +25,4 @@
"readme.md"
],
"private": false
}
}

View File

@ -36,6 +36,38 @@ export default class Observable<T = any> {
constructor(private collect_intervall: number = 100) { }
subscribe(callback: ObserverCallback<T>) {
if (this[ClosedSymbol])
throw new Error("Observable is closed!");
let oldcb = this.subscriber.find(e => e === callback);
if (!oldcb)
this.subscriber.push(callback)
}
unsubscribe(callback: ObserverCallback<T> | ObserverCallbackCollect<T>) {
if (this[ClosedSymbol])
return;
let idx = this.subscriber.findIndex(e => e === callback);
if (idx >= 0) {
this.subscriber.splice(idx, 1);
} else {
idx = this.subscriberCollect.findIndex(e => e === callback);
if (idx >= 0)
this.subscriberCollect.splice(idx, 1);
}
}
subscribeCollect(callback: ObserverCallbackCollect<T>) {
if (this[ClosedSymbol])
throw new Error("Observable is closed!");
let oldcb = this.subscriberCollect.find(e => e === callback);
if (!oldcb)
this.subscriberCollect.push(callback)
}
/**
* Creates Public API with subscribe and unsubscribe
*
@ -45,35 +77,9 @@ export default class Observable<T = any> {
if (this[ClosedSymbol])
throw new Error("Observable is closed!");
return {
subscribe: (callback: ObserverCallback<T>) => {
if (this[ClosedSymbol])
throw new Error("Observable is closed!");
let oldcb = this.subscriber.find(e => e === callback);
if (!oldcb)
this.subscriber.push(callback)
},
unsubscribe: (callback: ObserverCallback<T> | ObserverCallbackCollect<T>) => {
if (this[ClosedSymbol])
return;
let idx = this.subscriber.findIndex(e => e === callback);
if (idx >= 0) {
this.subscriber.splice(idx, 1);
} else {
idx = this.subscriberCollect.findIndex(e => e === callback);
if (idx >= 0)
this.subscriberCollect.splice(idx, 1);
}
},
subscribeCollect: (callback: ObserverCallbackCollect<T>) => {
if (this[ClosedSymbol])
throw new Error("Observable is closed!");
let oldcb = this.subscriberCollect.find(e => e === callback);
if (!oldcb)
this.subscriberCollect.push(callback)
}
subscribe: (callback: ObserverCallback<T>) => this.subscribe(callback),
unsubscribe: (callback: ObserverCallback<T> | ObserverCallbackCollect<T>) => this.unsubscribe(callback),
subscribeCollect: (callback: ObserverCallbackCollect<T>) => this.subscribeCollect(callback)
}
}