RxJS 速查
by Ash Norseman
Creating Observables
Ajax calls
Rx.DOM.get('/api/contents.json').subscribe(
function onNext(data) {
console.log(data.response);
},
function onError(err) {
console.error(err);
}
);
Array
Rx.Observable
.from([ 'Adrià', 'Jen', 'Sergi' ])
.subscribe(
function (x) {
console.log('Next: ' + x);
},
function (err) {
console.log('Error:', err);
},
function () {
console.log('Completed');
}
);
Range
Rx.Observable.range(1, 5);
Event
var allMoves = Rx.Observable.fromEvent(document, 'mousemove');
allMoves.subscribe(function (e) {
console.log(e.clientX, e.clientY);
});
var movesOnTheRight = allMoves.filter(function (e) {
return e.clientX > window.innerWidth / 2;
});
var movesOnTheLeft = allMoves.filter(function (e) {
return e.clientX < window.innerWidth / 2;
});
movesOnTheRight.subscribe(function (e) {
console.log('Mouse is on the right:', e.clientX);
});
movesOnTheLeft.subscribe(function (e) {
console.log('Mouse is on the left:', e.clientX);
});
Callback Function
var Rx = require('rx');
var fs = require('fs');
var readdir = Rx.Observable.fromNodeCallback(fs.readdir);
var source = readdir('/Users/sergi');
var subscription = source.subscribe(
function (res) {
console.log('List of directories: ' + res);
},
function (err) {
console.log('Error: ' + err);
},
function () {
console.log('Done!');
});
Interval
Rx.Observable.interval(1000);
Operators
var logValue = function (val) {
console.log(val)
};
map
var src = Rx.Observable.range(1, 5);
var upper = src.map(function (name) {
return name * 2;
});
upper.subscribe(logValue);
filter
var isEven = (function (val) {
return val % 2 !== 0;
});
var src = Rx.Observable.range(1, 5);
var even = src.filter(isEven);
even.subscribe(logValue);
reduce
var src = Rx.Observable.range(1, 5);
var sum = src.reduce(function (acc, x) {
return acc + x;
});
sum.subscribe(logValue);
scan
var avg = Rx.Observable.interval(1000)
.scan(function (prev, cur) {
return {
sum: prev.sum + cur,
count: prev.count + 1
};
}, { sum: 0, count: 0 })
.map(function (o) {
return o.sum / o.count;
});
var subscription = avg.subscribe(function (x) {
console.log(x);
});