Skip to content

Instantly share code, notes, and snippets.

@sohale
Last active September 29, 2016 15:51
Show Gist options
  • Save sohale/484e67f18c64d4f091aed4b4ab2642b5 to your computer and use it in GitHub Desktop.
Save sohale/484e67f18c64d4f091aed4b4ab2642b5 to your computer and use it in GitHub Desktop.
A very simple example usage of RxJS 5 to get the idea of what is does.
<!DOCTYPE html>
<!-- Playing with RxJS 5.0 -->
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Buffer</title>
<script src="https://npmcdn.com/@reactivex/[email protected]/dist/global/Rx.umd.js"></script>
</head>
<body>
Click anywhere on the page!
<hr>
Live output:
<br/>
<tt>clockstream.buffer(clickstream)</tt>: <br/>
<input id="inputbox1" style="font-size: 10px; background-color: #f0f0f0; border-width: 0px;" />
<br/>
<tt>clockstream.scan((acc,curr) => acc+1, 0)</tt>:</br>
<input id="inputbox2" style="font-size: 10px; background-color: #f0f0f0; border-width: 0px;" />
<br/>
<tt>clockstream.bufferCount(20)</tt>. <span style="color: #aaa;" >Also console.log()</span>
<br/>
<input id="inputbox3" style="font-size: 10px; background-color: #f0f0f0; border-width: 0px; width: 70%;" />
<hr>
Based on <a href="https://gist.github.com/btroncone/d6cf141d6f2c00dc6b35#buffer">this page</a>.
<script type="text/javascript">
const inputbox1 = document.getElementById("inputbox1");
const inputbox2 = document.getElementById("inputbox2");
const inputbox3 = document.getElementById("inputbox3"); // This is identical to console.log
const clockstream = Rx.Observable.interval(30);
const clickstream = Rx.Observable.fromEvent(document, 'click');
/*
Collect all values emitted by our interval observable until we click document. This will cause the clickstream Observable to emit a value. Pass us all collected values since last buffer as an array.
*/
const q20 = clockstream.bufferCount(20);
const _screr =
q20.subscribe(val => {
console.log(' Buffered Values:', val);
});
q20.subscribe(val => {
inputbox3.value = val;
});
// buffer()
// multiple events that are gathered in a queue, are sent suddenly together in an array val
// This sudden is triggered by clickstream.
// shown on screen
clockstream.buffer(clickstream).
subscribe(val => {inputbox1.value = val;inputbox1.style.width=(20*val.length)+"px";});
var q = clockstream.scan((acc, curr) => acc + 1, 0).
subscribe(val => {
inputbox2.value = val;
inputbox2.style.width=(20*(val % 10 + 10))+"px";});
// Note that the .subscribe() callback does not return anything.
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment