Skip to content

Instantly share code, notes, and snippets.

@WeslyG
Created January 24, 2023 12:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save WeslyG/8ad8b5775edc5097aecc47be163712f3 to your computer and use it in GitHub Desktop.
Save WeslyG/8ad8b5775edc5097aecc47be163712f3 to your computer and use it in GitHub Desktop.
'use strict';
class Observable {
constructor(subscribe) {
this.observers = [];
if (subscribe) {
subscribe(this)
}
}
subscribe(observer) {
const index = this.observers.push(observer);
const del = () => {
this.observers.splice(index -1, 1)
}
return {
...this,
unsubscribe() {
del()
}
};
}
next(data) {
if (this.observers.length === 0) return;
for (const observer of this.observers) {
observer(data);
}
}
}
const randomChar = () => String
.fromCharCode(Math.floor((Math.random() * 25) + 97));
// Usage
const sourceStream = new Observable(subscriber => {
setInterval(() => {
const char = randomChar();
subscriber.next(char);
}, 200);
});
let count = 0;
const observer = (char) => {
process.stdout.write(`${char}\n`);
count++;
if (count > 50) {
process.stdout.write('\n\n');
process.exit(0);
}
};
const subscription = sourceStream.subscribe(observer);
sourceStream.subscribe(observer)
setTimeout(() => {
subscription.unsubscribe()
}, 1000)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment