Last active
June 13, 2019 20:31
-
-
Save krystalmonolith/7eb6d03aa1805fb6ad0893d7c2e7fba9 to your computer and use it in GitHub Desktop.
RxJS delayWhen example enhanced with clicks queued/completed and delays displayed.
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
import { fromEvent, interval } from 'rxjs'; | |
import { delayWhen, map, tap, scan, debounce } from 'rxjs/operators'; | |
let queued: number = 0; | |
let completed: number = 0; | |
const start = Date.now(); | |
const clicks = fromEvent(document, 'click'); | |
function tf(): number { return Date.now() - start }; | |
const clickMsgs = clicks.pipe( | |
debounce(() => interval(100)), | |
scan(x => { queued = x + 1; return queued} , 0), | |
map(x => { return { msg: `Click ${x}`, delay: Math.floor(Math.random() * 5000) } } ) | |
); | |
const delayedClicks = clickMsgs.pipe( | |
map(x => { x['est'] = tf() + x.delay; return x}), | |
tap(x => console.log(`>>>[${tf()}: ${queued}/${completed}]: ${JSON.stringify(x)} >>>`)), | |
delayWhen(x => interval(x.delay)) | |
); | |
delayedClicks.subscribe(x => { | |
completed++; | |
console.log(`<<<[${tf()}: ${queued}/${completed}]: ${JSON.stringify(x)} <<<`) | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output: