Skip to content

Instantly share code, notes, and snippets.

@sylvainpolletvillard
Created May 11, 2020 16:15
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 sylvainpolletvillard/0fd9f0f6550b4d98b9762c2afeacea87 to your computer and use it in GitHub Desktop.
Save sylvainpolletvillard/0fd9f0f6550b4d98b9762c2afeacea87 to your computer and use it in GitHub Desktop.
eager timerObservable
function timer(delay){
const subscribers = []
let count = 0
const interval = setInterval(() => {
subscribers.forEach(observer => observer.next(count))
count++;
}, delay)
const timerObservable = {
subscribe: observer => {
subscribers.push(observer)
return {
unsubscribe: () => subscribers.splice(subscribers.indexOf(observer), 1)
}
}
}
return timerObservable
}
const interval = timer(1000)
const sub1 = interval.subscribe({
next: (val) => console.log("sub1", val)
})
setTimeout(() => {
const sub2 = interval.subscribe({
next: (val) => console.log("sub2", val)
})
}, 1500)
setTimeout(() => {
sub1.unsubscribe()
}, 3500)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment