Working with Observable in angular
Observable has now become most important part of Rxjs. It provides data sharing in asynchronous programming. here are many reasons we prefer using observable instead of promise. Observable can be accessed anywhere in the application, the only way to access it by subscribing it.
An Observable is like a stream and it allows us to send one or more events at a time. it is up to your requirement if you want to handle 0, 1 or a number of events, same API can be utilized for each event.
Observable has more advantages over promise. it can only be accessed or handled if you subscribe to it and that why Observables are called lazy. but if we talk about promise , it starts immediately and that can be caused as memory leakage. Observable has a powerful feature over promise to be cancellable, If there is no further need of the async operation then subscription of the observable allows us to cancel or complete the process in Angular.
We can use various Rxjs operators like map, pipe, reduce and more where every individual stream can be mapped or modified to get the desired data.
There are around 110 operators in Rxjs
Lets go more deep into Observable behavior, For that we need to understand Observers.
Observers are special types of function that we pass into subscribe to get expected outputs from Observable and this is quite simple we have three Observers next(), error() and complete() in an observables. when an Observable produces value it informs Observer next(), when an error occurs then error() get called and when there is no more value to be sent from Observable then it calls complete().
// Create simple observable that emits three values
const myObservable = of(1, 2, 3);
// Create observer object
const myObserver = {
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'),
};
// Execute with the observer object
myObservable.subscribe(myObserver);
// Logs:
// Observer got a next value: 1
// Observer got a next value: 2
// Observer got a next value: 3
// Observer got a complete notification
Creating Rxjs observable
Convert String to Observable
var obs = Observable.of('one', 'two', 'three');
obs.subscribe(
res => console.log(res),
err => console.log(err),
() => console.log('Completed!')
);
output:
one
two
three
Convert integer to Observable
Convert an Array to Observable
const array3 = [1, 2, 3, 4, 5, 6, 7]
const obsfrom1 = from(array3);
obsfrom1.subscribe(val => console.log(val),
error => console.log("error"),
() => console.log("complete"))
1 Comments
Test
ReplyDelete