Skip to content

Instantly share code, notes, and snippets.

@mrspeaker
Last active August 29, 2015 14:26
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 mrspeaker/4c8cdc1a4014c9d0762d to your computer and use it in GitHub Desktop.
Save mrspeaker/4c8cdc1a4014c9d0762d to your computer and use it in GitHub Desktop.
Rx streams
<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>
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