Reactive Programming is a pattern of development that works with asynchronous
data stream created of UI Events, HTTP Requests, File System, cache etc. So
data stream is an ongoing event sequence in time orderly manner. Stream can
emit value, error, and status signal.
Observables are to watch these streams and trigger function
on anything occurs in the stream. Observers can subscribe to observables.
RxJs is the library which helps us to do the exact same
implementation in our project.
As per MSDN -
Reactive Extensions (Rx) is a library for composing asynchronous and
event-based programs using observable sequences and LINQ-style query operators.
Reactive Extensions represents all these data sequences as observable
sequences. An application can subscribe to these observable sequences to
receive asynchronous notifications as new data arrive.
Great let’s see some RxJs Code and see how it works -
Example 1 –
import Rx from 'rxjs/Rx'; //import Rxjs
const src$ = new Rx.Observable.create(function (observer)
{ //Create observable
// Each next inside Observable will trigger subscribed
function.
observer.next('hi');
observer.next('hello');
setTimeout(function () {
observer.next('bye');
observer.complete();// Will end the observer
}, 3000);
//observer.error(new Error('Error'));// <-- uncomment the throw error
});
src$.subscribe(
function (e) {
console.log(e);// will execute when any change in Observable
},
function (er) {
console.log(er);// will be called when error
}, function () {
console.log('completed'); // will be called when done
}
);
See comments for detail understanding.
See running example here - https://jsfiddle.net/subhadipghosh/x3natp6y/
Few more examples.
Example 2 – (Event Observable)
import $ from 'jquery'; //import jquery
import Rx from 'rxjs/Rx'; //import Rxjs
const btn = $('#btn'); // get element
const input = $('#inp');
const btnStream$ = Rx.Observable.fromEvent(btn, 'click'); //
set observable event
btnStream$.scbscribe( // Subscribe to the event, to call
function when event occurs
function (e) {
console.log(e);
},
function (er) { //
error handling
console.log(err);
}, function () {
// called when completed
//completed
});
const inputStream$ = Rx.Observable.fromEvent(input, 'keyup');
btnStream$.scbscribe(
function (e) {
console.log(e);
},
function (er) {
console.log(err);
}, function () {
//completed
});
Example 3- (Observable Array)
import Rx from 'rxjs/Rx';
const numbers = [1, 2, 3, 4, 5];
const numberStream$ = Rx.Observable.from(numbers);// Make
array Observable
numberStream$.subscribe( // Subscribe to the array
observable
function (e) {
console.log(e);
},
function (er) {
console.log(err);
}, function () {
//completed
});
Further study - https://xgrommx.github.io/rx-book/why_rx.html
No comments:
Post a Comment