hydrogen-web/src/observable/BaseObservable.ts

85 lines
2.2 KiB
TypeScript
Raw Normal View History

2020-08-05 22:08:55 +05:30
/*
Copyright 2020 Bruno Windels <bruno@windels.cloud>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// we return undefined so you can reassign any member
// that uses `member?: T` syntax in one statement.
export type SubscriptionHandle = () => undefined;
2021-09-30 05:57:31 +05:30
export abstract class BaseObservable<T> {
protected _handlers: Set<T> = new Set<T>();
2019-02-22 03:38:23 +05:30
2021-09-30 05:57:31 +05:30
onSubscribeFirst(): void {
2019-02-22 03:38:23 +05:30
}
2021-09-30 05:57:31 +05:30
onUnsubscribeLast(): void {
2019-02-22 03:38:23 +05:30
}
subscribe(handler: T): SubscriptionHandle {
2019-02-22 03:38:23 +05:30
this._handlers.add(handler);
if (this._handlers.size === 1) {
2019-02-22 03:38:23 +05:30
this.onSubscribeFirst();
}
return () => {
2020-04-29 13:40:20 +05:30
return this.unsubscribe(handler);
2019-02-22 03:38:23 +05:30
};
}
unsubscribe(handler?: T): undefined {
2020-04-29 13:40:20 +05:30
if (handler) {
this._handlers.delete(handler);
if (this._handlers.size === 0) {
this.onUnsubscribeLast();
}
}
return undefined;
2020-04-29 13:40:20 +05:30
}
2021-09-30 05:57:31 +05:30
unsubscribeAll(): void {
if (this._handlers.size !== 0) {
this._handlers.clear();
this.onUnsubscribeLast();
}
}
2021-09-30 05:57:31 +05:30
get hasSubscriptions(): boolean {
return this._handlers.size !== 0;
}
// Add iterator over handlers here
2019-02-22 03:38:23 +05:30
}
export function tests() {
2021-09-30 05:57:31 +05:30
class Collection extends BaseObservable<{}> {
2021-10-01 13:32:32 +05:30
firstSubscribeCalls: number = 0;
2021-09-30 05:57:31 +05:30
firstUnsubscribeCalls: number = 0;
onSubscribeFirst() { this.firstSubscribeCalls += 1; }
onUnsubscribeLast() { this.firstUnsubscribeCalls += 1; }
}
return {
test_unsubscribe(assert) {
const c = new Collection();
2019-07-29 14:29:49 +05:30
const unsubscribe = c.subscribe({});
unsubscribe();
assert.equal(c.firstSubscribeCalls, 1);
assert.equal(c.firstUnsubscribeCalls, 1);
}
}
}