Here I discuss about reactive programming, observable, observer and difference between observable and promise.
Also discuss some of important operators like forkJoin, switchMap, from, deboucneTime, discardUntilChanged, mergeMap. I discuss some of observable creation function.
2. What we discuss?
➔ What is Rx & RxJS?
➔ What is Observable?
➔ What is Subscribing?
➔ Observable vs Promise
➔ Subscribe method shorthand notation
➔ What are the Observable creation function
➔ Why RxJS?
➔ Operators
◆ fromEvent, from, ajax, interval
◆ Subject, BehaviorSubject
◆ Filter, map, debounceTime, distinctUntilChanged
◆ forkJoin, mergeMap, switchMap
3. What is Rx?
➔ Rx is an API for asynchronous programming with observable streams.
➔ ReactiveX is a combination of the best ideas from the Observer pattern, the
Iterator pattern, and functional programming.
4. What is RxJS?
➔ JavaScript library
➔ Composing asynchronous and callback-based code in a functional, reactive
style using Observables.
➔ Many APIs such as HttpClient produce and consume RxJS Observables
5. What is Observable?
➔ A unique Object similar to promise
➔ It can help manage async code
➔ Stream of data
➔ Lazy Push collections of multiple values.
➔ It’s not part of JS language, so we need a popular Observable library called
RxJS
6. Observable Creation Example
import { Observable } from 'rxjs';
const observable = new Observable(observer => {
setTimeout(() => {
observer.next('Hello from a Observable!');
}, 2000);
});
7. What is Subscribing?
➔ An Observable instance begins publishing values only when someone
subscribes to it.
➔ So you need to subscribe by calling the subscribe() method of the instance
10. Observable vs Promise
Observable Promise
Computation does not start until
subscription so that they can be run
whenever you need the result
Execute immediately on creation
Provide multiple values over time Provide only one
11. Pull vs Push
➔ Pull and Push are two different protocols that describe how a data Producer
can communicate with a data Consumer.
➔ Every JavaScript Function is a Pull system.
12. Subscribe method shorthand notation
The subscribe() method can accept callback function definitions in line, for next, error, and complete
handlers is known as shorthand notation.
observable.subscribe({
next(x){console.log('Observer got a next value: ' + x)},
error(err){console.error('Observer got an error: ' + err)},
complete(){console.log('Observer got a complete notification')}
});
13. What are the Observable creation function
RxJS creating observables from things such as Promises, Ajax requests, Timers,
Events.
1. from ( Promise )
2. ajax ( Ajax )
3. interval ( Timers )
4. fromEvent ( Events )
14. 1. Create an observable from a promise
import { from } from 'rxjs'; // from function
const data = from(fetch('/api/endpoint')); //Created from Promise
data.subscribe({
next(response) { console.log(response); },
error(err) { console.error('Error: ' + err); },
complete() { console.log('Completed'); }
});
15. 2. Create an observable that creates an AJAX request
import { ajax } from 'rxjs/ajax'; // ajax function
const apiData = ajax('/api/data'); // Created from AJAX request
// Subscribe to create the request
apiData.subscribe(res => console.log(res.status, res.response));
16. 3. Create an observable from a counter
import { interval } from 'rxjs'; // interval function
const secondsCounter = interval(1000); // Created from Counter value
secondsCounter.subscribe(n => console.log(`Counter value: ${n}`));
17. 4. Create an observable from an event
import { fromEvent } from 'rxjs';
const el = document.getElementById('custom-element');
const mouseMoves = fromEvent(el, 'mousemove');
const subscription = mouseMoves.subscribe((e: MouseEvent) => {
console.log(`Coordnitaes of mouse pointer: ${e.clientX} * ${e.clientY}`);
});
22. Operators
➔ Operators are functions.
➔ RxJS is mostly useful for its operators
➔ It allow complex asynchronous code to be easily composed in a declarative
manner.
Two kind of operators:
1. Pipeable Operators
2. Creation Operators
25. Subject Continue ...
➔ An RxJS Subject is a special type of Observable
➔ It allows values to be multicasted to many Observers
➔ ...only upcoming values
import { Subject } from 'rxjs';
const subject = new Subject<number>();
subject.subscribe({
next: (v) => console.log(`observerA: ${v}`)
});
subject.subscribe({
next: (v) => console.log(`observerB: ${v}`)
});
subject.next(1);
26. BehaviorSubject
➔ Special type of Subject
➔ It has initial value
➔ It will emit the last value for new observer
➔ ...one previous value and upcoming values
33. forkJoin()
➔ When all observables complete, emit the last emitted value from each.
➔ Why use forkJoin?
forkJoin(
// as of RxJS 6.5+ we can use a dictionary of sources
{
google: ajax.getJSON('https://api.github.com/users/google'),
microsoft: ajax.getJSON('https://api.github.com/users/microsoft'),
users: ajax.getJSON('https://api.github.com/users')
}
)
// { google: object, microsoft: object, users: array }
.subscribe(console.log);
34. Other operators
➔ take(1) ( Emit provided number of values before completing. )
➔ takeUntil() ( until provided observable emits. )
➔ takeWhile() ( until provided expression is false. )
➔ first() ( Emit the first value )
➔ scan()
➔ reduce()