Last active
August 29, 2015 14:26
-
-
Save mrspeaker/4c8cdc1a4014c9d0762d to your computer and use it in GitHub Desktop.
Rx streams
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
<button class='refresh'>refresh</button> | |
<div> | |
<div id='s1'><span class='name'></span><span class='x'>X</span></div> | |
<div id='s2'><span class='name'></span><span class='x'>X</span></div> | |
<div id='s3'><span class='name'></span><span class='x'>X</span></div> | |
</div> | |
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
import Rx from 'rx'; | |
import $ from 'jquery'; | |
const refreshClicks = Rx.Observable.fromEvent($('.refresh')[0], 'click'); | |
const closesClicks = [1,1,1].map((x, i) => Rx.Observable.fromEvent($(`#s${i + 1} .x`)[0], 'click')); | |
const requests = refreshClicks | |
.startWith('init click') | |
.map(() => `https://api.github.com/users?since=${Math.random() * 500 | 0}`); | |
const responses = requests.flatMap(url => Rx.Observable.fromPromise($.getJSON(url))) | |
.publish() | |
.refCount(); | |
const usernames = responses.map(users => users.map(u => u.login)); | |
const suggestStream = stream => stream | |
.startWith('init close click') | |
.combineLatest(usernames, (click, u) => u[Math.random() * u.length | 0]) | |
.merge(refreshClicks.map(() => null)) // Map 'refresh' to null suggestions | |
.startWith(null); | |
const add = (num, u) => $(`#s${num} .name`).text(u || '---'); | |
const suggestStreams = closesClicks.map(clicks => suggestStream(clicks)); | |
suggestStreams.map((s, i) => s.subscribe(u => add(i + 1, u))); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment