Introduction to RxJS
A little about me
- Developer Expert for AngularJS
- JavaScript and AngularJS fanboy ^_^
- Blog | @tkssharma| github.com/tkssharma
- Community growing (sponsors, speakers)
Introduction
Asynchronous data streams
- Asynchronous, register a callback to be notified when results are available
- Data, raw information: Number, String, Objects (Arrays, Sets, Maps)
- Streams, sequences of data made available over time
Introduction
Basics
forEach/map/filter
for(var i=0, ii=team.length; i<ii; i+=1){
console.log(team[i].name);
}
team.forEach(function(member){
console.log(member.name);
});
var newTeam = [];
for(var i=0, ii=team.length; i<ii; i+=1){
newTeam.push(team[i]);
}
var onlyNames = team.map(function(member){
return { name: member.name };
});
var onlyOver100Commits = [];
for(var i=0, ii=team.length; i<ii; i+=1){
if (team[i].commits>100) {
onlyOver100Commits.push(team[i]);
}
}
var onlyOver100Commits = team
.filter(function(member){
return (member.commits>100);
});
reduce
var total = 0; // initial value
for(var i=0, ii=team.length; i<ii; i+=1){
total = total + team[i].commits;
}
var total = team
.reduce(function(total, member){
return total + member.commits;
}, 0);
composition
team
.filter(over100Commits)
.map(projectName)
.map(toUpperCase)
.forEach(log);
function over100Commits(member){
return (member.commits>100);
}
function projectName(member){
return member.name;
}
function toUpperCase(input){
return input.toUpperCase();
}
Basic Stream
----0----1----2----3----> rx.interval(5000)
$scope.counter = 0;
rx.Observable
.interval(5000)
.take(3)
.safeApply($scope, function(x) {
$scope.counter = x;
})
.subscribe(); // shows 0, 1, 2
Observable
Operations
Subscribe
Basic Stream
- Observable
- Operations
- merge, concat, map and more!
- Observer
- onNext, onError, onCompleted
- Subscribe/Unsubscribe
Key concepts
Basic Stream
observable.subscribe(
function onNext(value){
console.log(value);
},
function onError(error){
console.log(error);
},
function onCompleted(){
console.log('Completed');
});
var observer = rx.Observer.create(
function onNext(result){
console.log(result);
},
function onError(err){
console.log(err);
},
function onCompleted(){
console.log('Completed');
}
);
observable.subscribe(observer);
Observer
Basic Stream
var subscriber = observable.subscribe(observer);
$scope.$on("$destroy", function() {
subscriber.dispose();
});
Unsubscribe
Thanks
RX JS Promises Observables x.x
By tkssharma
RX JS Promises Observables x.x
- 887