Created
July 20, 2017 19:00
-
-
Save c0d0g3n/4a2cea6a4f74b5526f0ae23e214a5e82 to your computer and use it in GitHub Desktop.
Turn React events into rxjs streams (example: single click, double click...)
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
// stream of clicks | |
// onClick should call this.handleClick.bind(this) for it to work | |
const click$ = Observable | |
.create((observer) => { | |
// method puts clicks into stream | |
this.handleClick = (event) => { | |
observer.next(event) | |
} | |
}) | |
.share() // allow multiple branches | |
// stream of clicks that happen short after each other | |
const groupedClicks$ = click$ | |
.buffer(click$.debounceTime(250)) | |
.share() // allow multiple branches | |
// stream of lone clicks (at least 250ms before or after another click) | |
const singleClick$ = groupedClicks$ | |
.filter(clicks => clicks.length === 1) | |
// stream of double clicks | |
const doubleClick$ = groupedClicks$ | |
.filter(clicks => clicks.length === 2) | |
// ... | |
// inspired on: https://gist.github.com/mauriciosoares/5f7d185e900a23895e24 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment