Skip to content

Instantly share code, notes, and snippets.

@wardbell
Last active January 27, 2017 09:59
Show Gist options
  • Save wardbell/ea91e3fbb576988164e3c40fe81a14c3 to your computer and use it in GitHub Desktop.
Save wardbell/ea91e3fbb576988164e3c40fe81a14c3 to your computer and use it in GitHub Desktop.
My RxJS games
<!DOCTYPE html>
<html>
<head>
<meta name="description" content="RxJS Fun">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin RxJS Play</title>
<script src="https://unpkg.com/[email protected]/bundles/Rx.js"></script>
</head>
<body>
<div id="parent">
<div id="widget">Drag me</div>
</div>
</body>
</html>
console.clear();
const Observable = Rx.Observable;
////////////////////////////
// Basic
////////////////////////////
function basic() {
// 1. Event source.
function producer(callback) {
callback("Hello Observable");
}
// 2. Observable creation (Observable<int>)
var source = new Observable(observer => {
producer(value => observer.next(value));
observer.complete();
})
// 3. Observable execution.
source.subscribe( {
next: value => console.log(value),
complete:() => console.log('done')
});
}
basic();
////////////////////////////
// Basic - async
////////////////////////////
function basicAsync() {
// 1. Event source.
function producer(callback) {
var seed = 0;
return setInterval(() => callback(seed++), 500);
}
// 2. Observable creation (Observable<int>)
var source = new Observable(observer => {
const intervalId = producer(value => observer.next(value));
return () => clearInterval(intervalId);
})
// 3. Observable execution (subscribe [up to 10 events]).
source.take(10).subscribe( {
next: value => console.log(value),
complete: () => console.log("completed")
});
}
// basicAsync();
////////////////////////////
// Create
////////////////////////////
function create() {
var source = new Observable( observer => {
observer.next(42);
observer.complete();
});
// Subscribe with object
source.subscribe({
next: value => console.log('value: ' + value),
error: error => console.error('error: ' + error),
complete: () => console.log('done')
})
// Subscribe with fn parameters
source.subscribe(
value => console.log('value: ' + value),
error => console.error('error: ' + error),
() => console.log('done')
)
}
// create();
////////////////////////////
// Create - w/ error handling
////////////////////////////
function createEH() {
var source = new Observable( observer => {
try {
// throw 'deliberate error'
observer.next(84);
observer.complete();
} catch (err) {
observer.error(err);
}
});
source.subscribe(
value => console.log('value: ' + value),
error => console.error('error: ' + error),
() => console.log('done')
)
}
// createEH();
////////////////////////////
// Create Async
// Based on Ben Lesh, Egghead video
// https://egghead.io/lessons/rxjs-creating-an-observable
////////////////////////////
function createAsync() {
var source = new Observable( observer => {
var id = setTimeout( () => {
console.log('setTimeout hit')
try {
// throw 'deliberate error'
observer.next(128);
observer.complete();
} catch (err) {
observer.error(err);
}
}, 1000);
// disposer - enable or cancel won't work
// return () => clearTimeout(id);
});
/* Execute and hold on to return value (a subscription) */
const subscription = source.subscribe(
value => console.log('value: ' + value),
error => console.error('error: ' + error),
() => console.log('done')
)
/* Cancel Feature */
// setTimeout(() => {
// console.log('Cancel')
// subscription.unsubscribe();
// }, 500)
}
// createAsync();
////////////////////////////
// Drag & drop
// Based on Jafar Husain, Egghead video
// https://egghead.io/lessons/javascript-simple-drag-and-drop-with-observables
////////////////////////////
function dragAndDrop() {
var parent = document.getElementById('parent');
var widget = document.getElementById('widget');
var mouseDowns =
Observable.fromEvent(widget, 'mousedown')
.do(e => log('Mouse down', e));
var mouseMoves =
Observable.fromEvent(parent, 'mousemove')
.do(e => log('Mouse move', e));
var mouseUps =
Observable.fromEvent(parent, 'mouseup')
.do(e => log('Mouse up', e));
var drags = mouseDowns
// map each mouseDown into stream of mouseMoves until a mouseUp
.map(e => mouseMoves.takeUntil(mouseUps))
// flatten observables into one observable of mouse moves
.concatAll();
drags.subscribe(e => {
widget.style.left = e.clientX + 'px';
widget.style.top = e.clientY + 'px';
log('Dragged to', e);
});
function log(label, e) {
console.log(`${label}: ${e.clientX},${e.clientY}`);
}
}
// dragAndDrop();
////////////////////////////
// Observable vs. Promise
// Based on Ben Lesh, Egghead video
// https://egghead.io/lessons/rxjs-rxjs-observables-vs-promises
////////////////////////////
function promiseExample() {
var promise = new Promise(resolve => {
console.log('promise started');
setTimeout(() => {
console.log('promise event');
resolve(42);
}, 1000);
});
promise.then(val => console.log('promise value is ' + val));
// Second `then` uses the same promise result.
// Won't re-execute the producer logic.
// That's cool if you don't WANT it to re-execute.
// But can't be re-tried if there is an error.
promise.then(val => console.log('promise again'));
}
// promiseExample();
////////
function observableExample() {
var src = Observable.create( observer => {
console.log('observable started');
var id = setTimeout( () => {
console.log('observable event');
observer.next(42);
}, 1000);
return () => {
console.log('dispose called');
clearTimeout(id);
}
});
// now use it ... but cancel before it can deliver its value
var subscription =
src.subscribe(val => console.log('observable value is ' + val));
// ... but cancel before it can deliver its value
setTimeout(() => {
subscription.unsubscribe();
}, 500);
// 2nd subscription starts a new call to the observable
// This one is NOT cancelled.
src.subscribe(val => console.log('observable again'));
src.do(() => { throw new Error('deliberate error'); })
.subscribe(null , val => console.log('observable #3 errored'));
}
// observableExample();
////////////////////
function flatMapVersusMap() {
var source =
Observable.interval(100).take(10)
.flatMap(x => Observable.timer(500).map(() => x * 2))
//.mergeAll();
source.subscribe(x => console.log(x.toString()));
}
// flatMapVersusMap()
body {
font-family: Arial;
}
#parent {
background-color: red;
height: 200px;
width: 200px;
}
#widget {
background-color:blue;
color:white;
position:absolute;
width:150px;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment