What Is Rxjs Observable?

Observables are a core type of the reactive(RxJs) library. RxJs is extensively used in Angular (now Angular 7) framework. Observable provide us with asynchronous stream of data, that we can subscribe to, to get it’s values. In such a case, each time new data is emitted, we automatically get it in our stream. For instance, you have a chart of data, the chart data changes with user inputs. In such a case, as we use observables, we are sure our data is always updated and displayed in real time. If you have knowledge of promises, you are tempted to ask what then is the difference between observables and promises?

  • Observables return multiple values while a promise returns just a single value.
  • Observables are cancellable while promises are not
  • Observables can be manipulated using javascript array inspired functions known as operators such as `map, switchMap, filter` ..etc.

How to create an Observable

1
2
3
4
5
6
7
8
import { Observable } from 'rxjs'; 
 const foo = Observable.create(function (observer) { 
 console.log('Hello'); observer.next(42); 
}); 

foo.subscribe(function (x) { 
 console.log(x); 
}); // logs "Hello" 42 

Observables as a javascript Push system?

In Push systems, the Producer determines when to send data to the Consumer. The Consumer is unaware of when it will receive that data.

Promises are the most common type of Push system in JavaScript today. A Promise (the Producer) delivers a resolved value to registered callbacks (the Consumers), but unlike functions, it is the Promise which is in charge of determining precisely when that value is "pushed" to the callbacks.

RxJS introduces Observables, a new Push system for JavaScript. An Observable is a Producer of multiple values, "pushing" them to Observers (Consumers). A Function is a lazily evaluated computation that synchronously returns a single value on invocation.

A generator is a lazily evaluated computation that synchronously returns zero to (potentially) infinite values on iteration.

A Promise is a computation that may (or may not) eventually return a single value. An Observable is a lazily evaluated computation that can synchronously or asynchronously return zero to (potentially) infinite values from the time it's invoked onwards.

Related Posts

0 Comments

12345

    00