What is an Observable in Rxjs

·

5 min read

What is an Observable in Rxjs

According to the definition, Observables defined as lazy Push collections of multiple values.

Don't confuse, Now just bear with me, soon all your doubts will be gone. Before Diving into understanding the Observables, lets understand two strategies or protocols PUSH & PULL used in the programming languages. Now when you write some code, it means some code is producing some data & other code is going to consume it. So in simple terms we may have a Data-Producer, which produce the data and Data-Consumer who is just going to consume it.

So let's take an example to understand Producer and Consumer.

Let suppose we have a function sum & some code is calling it.

 // producer
  function foo() {
  return 1;
  }

  // consumer
  const val = foo();
  console.log(val);

Here, you can simply say that function foo is producing data, So you can consider it as a Producer. And the below code is calling foo to consume the data, So it you can consider it as a Consumer.

Now, Now we are comfortable with Data Producer & Data Consumer as well.

Now let's discuss the PUSH & PULL system.

  • PULL System: In PULL system, Producer produce data when requested & consumer decides when it should be requested. If you see the above example, you can observe, that foo method is producing the data only when called. So in the above case,Consumer is the main aspect who will decide when to request data.
  • PUSH strategy: Producer produces data on the basis of its availability & Consumer can react only to receive the data. Let's take an example. Promise is the simplest type of Push system in JavaScript.

Taking the above example but with Promise & let's rewriting it again -

// Producer
function func() {
  return new Promise(resolve => {
  setTimeOut(()=>{
      return resolve(1); 
  }
)
});

// Consumer
const value = func().then(data=>{
    console.log(data);
})

So as you can see, Now the consumer can react to the the producer only, but don't have authority to request the data from the Producer. Here is the Producer is the active main aspect which decide when to send the data on the availability of the data. So once the data is available, it can be received via Callback. Or it can also be possible that data never available to the Producer & as a result it didn't send. Because now only Producer define when to send the data.

Now may be you got an idea about PULL & PUSH systems as well. So let's continue with Observable.

So you can consider Observable as a advance Push system, it means it is Observable who decide when to send/produce the data to the consumer once consumer reacts/subscribes to it.

But unlike Promise it can produce multiple values or you can say Observable is a producer of multiple values. And that a point of sale for Observable's. It can produce multiple value synchronously as well asynchronously.

We will understand this thing with the help of an example.

As we already know that Observable is not supported natively by JavaScript, currently it is provided by the RxJs library. But there is an ongoing proposal for the native support for the Observable's. And may be we can find Observable as a native part of JavaScript in future.

So let's use Observable from RxJs library.

A typical synchronous observable is like as below -

import { Observable } from 'rxjs';

const observable = new Observable(subscriber => {
  subscriber.next(1); // next is used to produce the data;
  subscriber.next(2);
  subscriber.next(3);
});

If some code have to utilize the value produce/managed by our Producer (Observable), then that code or simply the consumer have to subscribe the observable. Ex:-

observable.subscribe({
  next(x) { console.log('got value ' + x); },
  error(err) { console.error('something wrong occurred: ' + err); },
  complete() { console.log('done'); }
})

OR we can write the above code as below as well

observable.subscribe(
  data=>{
    console.log('got value ' + x);
  },
  err=>{
    console.error('something wrong occurred: ' + err);
  },
  complete=> {
    complete() { console.log('done'); }
  }
);

And If you run this program, you will get output a

got value 1
got value 2
got value 3
done

When you subscribe to an observable, the observer/subscriber takes 3 arguments.

  • one is for data which sent via by calling next method from the producer.
  • second is error,if any error happens from the producer side.
  • Third is complete, when your producer finished to send the data to the consumer.

Now takes an Asynchronous Example -

const observable = new Observable(subscriber => {
   setTimeOut(()=>{subscriber.next(1);}, 1000);
   setTimeOut(()=>{subscriber.next(2);}, 3000);
   setTimeOut(()=>{subscriber.complete()}, 2000); // after 3 seconds complete 
});

observable.subscribe(
  data=>{
    console.log('got value ' + x);
  },
  err=>{
    console.error('something wrong occurred: ' + err);
  },
  complete=> {
    complete() { console.log('done'); }
  }
);


Output

1
done

The reason is that once your observable completes or throw an error then the consumer will not receive any data.

So now, I thinks you got the concept about Observables. But still if are unable to grab the concept, let me relate the observable to a very basic real scenario. And you can relate it to any scenario around you.

Everybody knows about Netflix. On Netflix there are third party content providers and as well Netflix Original content providers So these are are the Data Producer. Now, think Netflix OTT as an Observable which decide when to stream that data from these content providers. You as a subscriber have paid amount to the Netflix for monthly subscription service for viewing the content. Now here you & your family members will be act as the observers only who don't know when the new content is produced or not or simply when the new movie or some season will come. Here you can just observe only by reacting/observing through Netflix app/web. So App or web is just a observer object.

Now, this app/web can only do things in three manners

  • Streaming content - until unless Netflix server are capable of. So you are receiving the content.
  • Error/ No Content - let suppose, Netflix server down while streaming. So in that case, you are not able to receive the content.
  • Complete - Let's assume that your paid subscription expired or you have cancelled the subscription. So it means, your observable have been completed. And you are not able to access streaming until unless, you again subscribe it.

May be you got some understanding over observable.

Thanks

Happy Observable.