Created
July 15, 2022 00:19
-
-
Save jacoobes/c80312ca9d79426fb8cb91a2443b316f to your computer and use it in GitHub Desktop.
pub sub for events
This file contains hidden or 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 Channel<T> { | |
private subscribers : Subscriber<T>[] = []; | |
private values : T[] = []; | |
public emit(value : T) | |
{ | |
this.values.push(value); | |
} | |
public notify() | |
{ | |
for(const sub of this.subscribers) | |
{ | |
sub.update(this.values) | |
} | |
} | |
public addSubscriber(sub : Subscriber<T>) | |
{ | |
this.subscribers.push(sub) | |
} | |
} | |
class Subscriber<T> { | |
values : T[] = [] | |
public update(vals : T[]) { | |
this.values = vals; | |
} | |
public listen(cb : (value : T) => void) { | |
for(const val of this.values) | |
{ | |
cb(val) | |
} | |
} | |
} | |
const sub = new Subscriber<Record<string, string>>(); | |
const channel = new Channel<Record<string, string>>(); | |
channel.addSubscriber(sub); | |
const pingApi = setInterval(() => { | |
fetch('https://api.chucknorris.io/jokes/random') | |
.then(res => res.json()) | |
.then(json => { | |
channel.emit(json); | |
channel.notify(); | |
}); | |
}, 500); | |
sub.listen((joke: Record<string, string>) => { | |
console.log(joke.value) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment