Created
February 13, 2019 05:30
-
-
Save clinuxrulz/8beed7b8eb9fcad06807c039bdd9ec9c to your computer and use it in GitHub Desktop.
wake-up / sleep listeners
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Test<A> { | |
private _value: A; | |
private _listeners: ((a:A)=>void)[] = []; | |
private _onWakeUp: () => {}; | |
private _onSleep: () => {}; | |
public constructor(value: A) { | |
this._value = value; | |
} | |
public listen(listener: (a:A)=>void): ()=>void { | |
if (this._listeners.length == 0) { | |
this._onWakeUp(); | |
} | |
this._listeners.push(listener); | |
return () => { | |
for (var i = 0; i < this._listeners.length; ++i) { | |
if (this._listeners[i] === listener) { | |
this._listeners.splice(i, 1); | |
if (this._listeners.length == 0) { | |
this._onSleep(); | |
} | |
return; | |
} | |
} | |
}; | |
} | |
public map<B>(fn: (a:A)=>B): Test<B> { | |
var x = new Test( | |
fn(this._value) | |
); | |
x._onWakeUp = () => { | |
... | |
} | |
x._onSleep = ... | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment