Created
November 22, 2021 06:36
-
-
Save modeware/38f0d45ece7058044e96ce66c0183f1d to your computer and use it in GitHub Desktop.
Basic Observable Implementation From Scratch
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 Observable { | |
constructor(subscribe){ | |
this._subscribe = subscribe; | |
} | |
subscribe(observer){ | |
return this._subscribe(observer); | |
} | |
static timeout(time){ | |
return new Observable(function subscribe(observer){ | |
const handle = setInterval(function(){ | |
//observable calling the next method on the observer | |
observer.next() | |
observer.complete(); | |
}, time) | |
return { | |
unsubscribe(){ | |
clearInterval(handle) | |
} | |
} | |
}) | |
} | |
} | |
const obs = Observable.timeout(500) | |
console.log(obs) | |
const subscription = obs.subscribe( | |
//observer object | |
{ | |
next(v){ | |
console.log('next') | |
}, | |
complete(){ | |
console.log('complete') | |
} | |
} | |
) | |
setTimeout(() =>{subscription.unsubscribe()}, 5000) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment