Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
A refactor of André Staltz's example twitter program in his tutorial on RxJS: https://gist.github.com/staltz/868e7e9bc2a7b8c1f754
// UI Event Streams --------------------------------------------
const refreshButton = document.querySelector('.refresh');
const closeButton1 = document.querySelector('.close1');
const closeButton2 = document.querySelector('.close2');
const closeButton3 = document.querySelector('.close3');
const refreshClickStream = Rx.Observable.fromEvent(refreshButton, 'click');
const close1ClickStream = Rx.Observable.fromEvent(closeButton1, 'click');
const close2ClickStream = Rx.Observable.fromEvent(closeButton2, 'click');
const close3ClickStream = Rx.Observable.fromEvent(closeButton3, 'click');
// Helper Functions --------------------------------------------
const makeRequestUrl = () => {
const randomOffset = Math.floor(Math.random() * 500);
return `https://api.github.com/users?since=${randomOffset}`;
};
const getRandomUser = users =>
users[Math.floor(Math.random() * users.length)];
// Program Logic -----------------------------------------------
const requestStream = refreshClickStream
.startWith('startup click')
.map(makeRequestUrl);
const responseStream = requestStream
.flatMap(url => Rx.Observable.fromPromise($.getJSON(url)));
const createSuggestionStream = closeClickStream =>
closeClickStream
.startWith('startupclick')
.combineLatest(responseStream, (click, users) => getRandomUser(users))
.merge(refreshClickStream.map(() => null))
.startWith(null);
const suggestion1Stream = createSuggestionStream(close1ClickStream);
const suggestion2Stream = createSuggestionStream(close2ClickStream);
const suggestion3Stream = createSuggestionStream(close3ClickStream);
// Rendering ---------------------------------------------------
function renderSuggestion(suggestedUser, selector) {
const suggestionEl = document.querySelector(selector);
if (suggestedUser === null) {
suggestionEl.style.visibility = 'hidden';
} else {
suggestionEl.style.visibility = 'visible';
const usernameEl = suggestionEl.querySelector('.username');
usernameEl.href = suggestedUser.html_url;
usernameEl.textContent = suggestedUser.login;
const imgEl = suggestionEl.querySelector('img');
imgEl.src = "";
imgEl.src = suggestedUser.avatar_url;
}
}
suggestion1Stream.subscribe(function (suggestedUser) {
renderSuggestion(suggestedUser, '.suggestion1');
});
suggestion2Stream.subscribe(function (suggestedUser) {
renderSuggestion(suggestedUser, '.suggestion2');
});
suggestion3Stream.subscribe(function (suggestedUser) {
renderSuggestion(suggestedUser, '.suggestion3');
});
Owner

adrianmcli commented Jan 6, 2017

If you paste the above JS into the original JSBin example, it will work the same.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment