Skip to content

Instantly share code, notes, and snippets.

@evturn
Last active January 2, 2017 03:05
Show Gist options
  • Save evturn/f4a32420d8adc6b62dae91f4be500748 to your computer and use it in GitHub Desktop.
Save evturn/f4a32420d8adc6b62dae91f4be500748 to your computer and use it in GitHub Desktop.
Creating an Observable from scratch
function Observer(destination) {
this.destination = destination
}
Observer.prototype = {
constructor: Observer,
next(value) {
if (this.destination.next && !this.isUnsubscribed) {
this.destination.next && this.destination.next(value)
}
},
error(e) {
if (!this.isUnsubscribed) {
if (this.destination.error) {
this.destination.error(e)
}
this.unsubscribe()
}
},
complete() {
if (!this.isUnsubscribed) {
if (this.destination.complete) {
this.destination.complete()
}
this.unsubscribe()
}
},
unsubscribe() {
this.isUnsubscribed = true
if (this._unsubscribe) {
this._unsubscribe()
}
}
}
function Observable(_subscribe) {
this._subscribe = _subscribe
}
Observable.prototype = {
constructor: Observable,
subscribe(subscriber) {
const observer = new Observer(subscriber)
observer._unsubscribe = this._subscribe(observer)
return _ => observer.unsubscribe()
}
}
const a = [
'Fred',
'Quentin',
'idiot',
'Doug',
'tr0n',
'James',
'Bitchface',
'Maude',
'Gladys',
'Ploppy',
'Manuel',
'Greg'
]
const observable$ = new Observable((observer) => {
let i = 0
const id = setInterval(() => {
if (i < a.length) {
observer.next(`Sup ${a[i]}`)
i++
} else {
observer.complete()
}
}, 100)
return () => {
console.log('Are you sure you want to unsubscribe? Kidding, unsubscribed.')
clearInterval(id)
}
})
const observer = {
next(x) { console.log('next -> ' + x)},
error(err) {},
complete() { console.log('We are done diddly done!')}
}
const subscription$ = observable$.subscribe(observer)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment