element.addEventListener('click', event => {
if (event.x >= 100 && event.y >= 100) {
const doubleCoordinates = {
x: event.x * 2,
y: event.y * 2
};
console.log('2x:', doubleCoordinates.x, ' 2y': doubleCoordinates.y);
}
});
const clicks = [ { x: 10, y: 20}, ... ];
clicks
.filter(click => click.x >= 100 && click.y >= 100)
.map(click => { x: click.x * 2, y: click.y * 2 })
.forEach(doubleCoordinates => {
console.log('2X': doubleCoordinates.x, ' 2Y':, doubleCoordinates.y);
});
// For each click event
element.addEventListener('click', event => {
// Filter it if does not pass a given predicate
if (event.x >= 100 && event.y >= 100) {
// Map it (Transform it)
const doubleCoordinates = {
x: event.x * 2,
y: event.y * 2
};
// Do something with it
console.log('2x:', doubleCoordinates.x, ' 2y': doubleCoordinates.y);
}
});
Hallo!
doAsync(param, (result, error) => {
if (!error) {
doAnotherAync(result, (anotherResult, anotherError) => {
if (!anotherError) {
doSomething(anotherResult);
}
else {
console.err(anotherError);
}
});
}
else {
console.err(error);
}
});
doAsync(param)
.then(result => doAnotherAsync(result))
.then(result => doSomething(result))
.catch(error => console.err(error))
Click events happenning in time
// From Event
const clicks = Rx.Observable.fromEvent(document, 'click');
// From Promise
const getJoke = Rx.Observable.fromPromise(
fetch('https://api.icndb.com/jokes/random')
);
// From Callback
const fromCallback = Rx.Observable.bindCallback(fnWithCallbackAtLast);
// From Array
const fromArray = Rx.Observable.from([1,2,3,4]);
// From Range
const range = Rx.Observable.range(1,5);
const simpleObservable = Rx.Observable.create(observer => {
let counter = 0;
const handler = setInterval(() => {
// Produce a random value
observer.next(Math.random());
counter++;
if (counter === 6) {
// Completes the sequence
observer.complete();
}
}, 500);
// Return an unsubscribe method so we can cancel
return () => {
clearInterval(handler);
}
});
const subscription = simpleObservable
.subscribe(
randomNumber => console.log(randomNumber), // onNext,
err => console.log('error'),
() => console.log('Completed')
);
We subscribe to an Observable passing an Observer
An observer is just a set of 3 functions:
// When we call subscripe, we get a Subscription object
// which has an unsubscribe method
const subscription = simpleObservable
.subscribe(
randomNumber => console.log(randomNumber), // onNext,
err => console.log('error'),
() => console.log('Completed')
);
A subscription esentially has an unsubscribe function to release resources or cancel an Observable
subscription.unsubscribe();
Transformation Operators
Filtering Operators
Combination Operators
With some others, also small, using it
Pros
Cons
and ask something, i'll try to answer! :D