2020-04-21 00:56:39 +05:30
|
|
|
export class BaseObservable {
|
2019-02-22 03:38:23 +05:30
|
|
|
constructor() {
|
|
|
|
this._handlers = new Set();
|
|
|
|
}
|
|
|
|
|
|
|
|
onSubscribeFirst() {
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
onUnsubscribeLast() {
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
subscribe(handler) {
|
|
|
|
this._handlers.add(handler);
|
2019-02-27 01:43:43 +05:30
|
|
|
if (this._handlers.size === 1) {
|
2019-02-22 03:38:23 +05:30
|
|
|
this.onSubscribeFirst();
|
|
|
|
}
|
|
|
|
return () => {
|
|
|
|
if (handler) {
|
2019-07-29 14:29:07 +05:30
|
|
|
this._handlers.delete(handler);
|
2019-02-27 01:43:43 +05:30
|
|
|
if (this._handlers.size === 0) {
|
2019-02-22 03:38:23 +05:30
|
|
|
this.onUnsubscribeLast();
|
|
|
|
}
|
|
|
|
handler = null;
|
|
|
|
}
|
|
|
|
return null;
|
|
|
|
};
|
|
|
|
}
|
2019-02-27 01:18:57 +05:30
|
|
|
|
|
|
|
// Add iterator over handlers here
|
2019-02-22 03:38:23 +05:30
|
|
|
}
|
2019-07-29 14:28:27 +05:30
|
|
|
|
|
|
|
export function tests() {
|
2020-04-19 22:32:10 +05:30
|
|
|
class Collection extends BaseObservable {
|
2019-07-29 14:28:27 +05:30
|
|
|
constructor() {
|
|
|
|
super();
|
|
|
|
this.firstSubscribeCalls = 0;
|
|
|
|
this.firstUnsubscribeCalls = 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();
|
2019-07-29 14:28:27 +05:30
|
|
|
assert.equal(c.firstSubscribeCalls, 1);
|
|
|
|
assert.equal(c.firstUnsubscribeCalls, 1);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|