How Observable works in RxJS?

What is Observable?

Observable is a like a stream which allow to pass zero or more events or values  and you can subscribe each using a callback function.

Why Observables are so important?

In almost all UI when user do some interactions with it you can see the same progression. for example

  • You are listening an event
  • You are making an asynchronous request to the server and may be you are follow up with some transformations or Animations

Observables are capable of modeling all the above things together with a very little code.

In order to understand how Observable works , look at the sample code

var observable = Observable.create(function(observer) {
var sum = 0;
for (var i = 1; i <= 4; i++) {
if (i <= 3) { sum = sum + i; observer.next(i); //You can emit each item from the observable also } if (i === 4) { setTimeout( i => {
observer.next(sum);
observer.complete();
},
5000,
i
);
}
}
});

In this sample code, I am running a for loop and emit each value by using observer.next(value) , when the value of i become 4 you can see emiting the sum of 3 numbers and exiting the all observable sequence by simple calling observable.complete();

Observables are lazy which means , the above code never executes unless you are subscribing it.

Let’s subscribe the Observable to get each value. I am removing the lambda expression to understand more clearly

observable.subscribe({
next: function(x) {
console.log("got value " + x);
},
error: err => console.error("something wrong occurred: " + err),
complete: function() {
//when I become 4 it will complete
console.log("completed");
}
});

In the callback function of next , you will get all the values emitted from the Observable sequence including sum as final value and finally execute the complete callback function.

You can simply receive each value like the below syntax also instead of specify next explicitly

observable.subscribe(function(x) {
//here you will get all the value including sum
console.log(x);
});

Let me tell you one more scenario with the same sample by simply commenting one line of code. I am not emitting each value instead I want to emit the sum only from the observable and complete.

var observable = Observable.create(function(observer) {
var sum = 0;
for (var i = 1; i <= 4; i++) {
if (i <= 3) { sum = sum + i; //commented the code } if (i === 4) { setTimeout( i => {
observer.next(sum);
observer.complete();
},
5000,
i
);
}
}
});

Now when you subscribe , you will have only one value , that is sum

observable.subscribe(function(x) {
//here you will the sum
console.log(x);
});

Official Documenation to learn about RxJS features
https://www.learnrxjs.io/


How to subscribe and unsubscribe the window load event in Rxjs

I know every web programmers are aware of adding window.addeventlistener to ensure some codes are executing once when loading the web page. You can remove the listener by removing using removeEventListener to make avoid the memory leak.

You can do the same thing in a RxJs fashion using take(1). So you no need to unsubscribe it explicitly to avoid the memory leak.
var onWindowLoad=Observable.fromEvent(window,'load');

var onLoadSubscription=onWindowLoad.take(1).forEach(function(event){
alert("onLoadFireEvent");
});

How Map and Filter function works in RXJS

In order to understand how Map and Filter works , we can implement our own map function.
Map
Map in Rxjs used for projection, means you can transform the array in to entirely new array.

Array.prototype.map = function(projectionFunction){
var results=[];
this.forEach(function(item) {
results.push(projectionFunction(item));
});
return results;
};

You can see I have written a map function which accepts an anonymous function as a parameter. This will be your function to apply the projection to transform the array. Inside the map function you can see iterating each item in a array , call the project function by passing each item and finally the result of the projection function will push to the results array.

JSON.stringify([1,2,3].map(function(x){return x+1;}))

Output
[2,3,4]

https://www.learnrxjs.io/operators/transformation/map.html

Filter
Filter is used to filter an array based on some condition. You can specify the condition through an anonymous function. The implementation of Filter and Map are almost same only the difference is Map will transform each item in an array and will push to the main array. But the filter will only push to the main array if the condition pass.
var hotelCollection = [
{
"id": 9999,
"name": "Hotel XXX",
"place": "Wayne",
"rating": 5.0
},
{
"id": 8888,
"name": "Hotel YYY",
"place": "WoodCliff Lake",
"rating": 4.5
},
{
"id": 7777,
"name": "Hotel ZZZ",
"place": "Franklin Lake",
"rating": 5.0
},
{
"id": 6666,
"title": "Hotel PPP",
"place": "Lancester",
"rating": 4.3
},
];

Source

Array.prototype.filter=function(predicateFunction){
var results=[];
this.forEach(element => {
if(predicateFunction(element)){
results.push(element)
}
});
return results;
}

var collection = hotelCollection.filter(x=>x.rating===5);
https://www.learnrxjs.io/operators/filtering/filter.html
Thanks for reading