Christopher Bloom, @illepic
A long running process that occasionally produces clicks that we may want to respond to. The clicks are a dataset stored across time.
Clicks
Keyboard
Websockets
Workers
AJAX
Callbacks
function doStuff(e) {
console.log(e.timeStamp);
}
$('#click-me').on('click', doStuff);
Promises
const myPromise = new Promise((resolve, reject) =>
setTimeout(() => resolve('flerp'), 300)
);
myPromise.then(val => console.log(val));
// fromEvent turns a browser event into an observable
import { fromEvent } from 'rxjs';
// Simple DOM reference
const button = document.getElementById('click-me');
// Create an observable of button clicks
const myObservable = fromEvent(button, 'click');
e
e
e
An observable represents a stream, or source of data that can arrive over time. The above "marble diagram" shows an observable created using fromEvent on a DOM element emitting clicks.
Observables don't do anything until ...
Subscriptions set everything in motion
// fromEvent turns a browser event into an observable
import { fromEvent } from 'rxjs';
// Simple DOM reference
const button = document.getElementById('click-me');
// Create an observable of button clicks
const myObservable = fromEvent(button, 'click');
// Do something with these clicks
const mySub = myObservable.subscribe(
e => console.log(e.timeStamp)
);
Subscriptions set everything in motion. We provide a function to the .subscribe() method. This function is also call the observer.
App
Subscription
Observable
import { of } from 'rxjs';
import { map } from 'rxjs/operators';
// Deliver values in a sequence (1 then 2 etc)
const dataSource = of(1, 2, 3, 4, 5);
// subscribe to our source observable
const subscription = dataSource
.pipe(
// add 1 to each emitted value
map(value => value + 1)
)
// log: 2, 3, 4, 5, 6
.subscribe(value => console.log(value));
"The lodash of reactive programming", Operators manipulate values from a source, returning an Observable of the transformed values. Operators are chained together to run complex manipulation on streams.
// observable of values from a text box,
// .pipe() chains operators together
inputValue
.pipe(
// wait for a 200ms pause
debounceTime(200),
// if the value is the same, ignore
distinctUntilChanged(),
// if an updated value comes through while request is still
// active cancel previous request and 'switch' to new observable
switchMap(searchTerm => typeaheadApi.search(searchTerm))
)
// create a subscription
.subscribe(results => {
// update the dom
});
The "assembly line" from your observable through your operators. The output Observable of one Operator becomes the input Observable to the next Operator.