RxJS Introduction
What is RxJS
**A utility library for streams of data
Javascript version of ReactiveX API to handle observable streams
- Observable: An observable represents a stream, or source of data that can arrive over time . Observables are cold.
- Observer: Observer is just set of callbacks consist of 3methods : next() , complete() , error()
- Subscription: Observable is nothing without subscription. Think of it as the faucet of water source (An observable). You get water when you turn the faucet open.
- Operators: Helper methods which are pure functions that help us to work with data. E.g map, filter, concat, flatMap, etc. Operators are the lodash version of Observables
- Subject: Way of multicasting a value or event to multiple Observers (will cover in a later demo session ;-) )
Fundamentals of RxJS
const myObservable = fromEvent(button, 'click');
Creating a observable from an event
Creating a observable using create()
const dataSource = of(1, 2, 3, 4, 5);
const hello = Observable.create(function(observer) {
observer.next('Hello');
observer.next('World');
observer.complete();
});
Creating a observable using of creation operator
Creating Observables
Subscription of Observables
const myObservable = fromEvent(button, 'click');
const subscription1 = myObservable.subscribe(event => console.log(event));
const subscription1 = myObservable.subscribe(event => console.log(event));
- Can have multiple subscriptions from a single observable source
Un-subscription of Observables
const myObservable = fromEvent(button, 'click');
const subscription = myObservable.subscribe(event => console.log(event));
const secondSubscription = myObservable.subscribe(event => console.log(event));
// clean up with unsubscribe
subscription.unsubscribe();
secondSubscription.unsubscribe();
- Make sure to un-subscribe your subscriptions to avoid potential memory leaks.
- No need to un-subscribe if you use complete().
Operators
- Creation operators
- Transformation operators
- Filtering operators
- Multicasting operators
- Errorhandling operators
- Utility operators
- Conditional operators
- Mathematical and aggregate operators
Real-world example of operators
Useful links
Thank you.
RxJS Basic Introduction
By salimmalik
RxJS Basic Introduction
Basic introduction to RxJS . Introduction to Observables , Observers , Subscriptions and Operators with sample code.
- 288