Created
May 11, 2020 16:15
-
-
Save sylvainpolletvillard/0fd9f0f6550b4d98b9762c2afeacea87 to your computer and use it in GitHub Desktop.
eager timerObservable
This file contains hidden or 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
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