Skip to content

Instantly share code, notes, and snippets.

@modeware
Created November 22, 2021 06:36
Show Gist options
  • Save modeware/38f0d45ece7058044e96ce66c0183f1d to your computer and use it in GitHub Desktop.
Save modeware/38f0d45ece7058044e96ce66c0183f1d to your computer and use it in GitHub Desktop.
Basic Observable Implementation From Scratch
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