Angular 2 RxJS – Observable

Angular 2 rxJS Observable is a library to deal with asynchronous data streams in angular 2 applications.

Angular 2 rxJS Observable why? Simply it’s the best way to deal with Streams! Oops Streams?  Yes! We will explain everything : )

angular 2 rxjs observable
angular 2 rxjs observable

 

The future  = Data Streams.

 Data Streams.
Data Streams.

In the future we will talk more about Data Streams and not only Data !

 

angular 2 observables promises
angular 2 observables promises

Asynchronous: Happen in the future. (E.g. we click and we wait something to happen)

Data: var myName = ‘Angular 2’. (Angular 2 is a Data we store in a variable)

Streams: We receive a chunk of data over time. (t0 , t1 , t3 … tn) and we don’t know how much time it will take to arrive. ; )

 

stream ?
stream ?

Let’s take an example to understand this notion of stream!

  • We have a Data Stream (the data stream we are waiting for stored somewhere): 1 , 2 , 3 , 4 , 5 , 6 , 7
  • We want to subscribe to this Stream : source.subscribe();
  • And every time a new push happens with new value (1 , 2 , 3 …)
  • First time we push (receive ) : 1
  • Second time we push (receive) : 2
  • Until the end.
  • You can see it as an Array : )

But the difference is: the array is already here.  [ 1, 2 , 3 , 4 , 5 , 6 , 7 ]

With Arrays: we are not waiting for something to arrive! (It’s in the memory)

Push and Pull
Push and Pull

 

Why we say Push?

  • Pull
  • Suppose you have an Array! [1 , 2 , 8]
  • You can Pull a value from this array.
  • Because it’s here and you can decide when to Pull a value.
  • Push

Now if you are waiting for something to arrive from a source : )

In this case you cannot decide when to do, but you just wait!

That’s why we talk about Push. The stream decides when to Push the new value.

Pull (Synchronous) Push (Asynchronous)
Arrays , iterate Promises , Observables
RxJs Observables
RxJs Observables

 

Before we get into RxJs Observables it’s pretty good to do a small revision about Arrays methods (forEach() , map() , filter() , reduce() )

  1. map() : it’s like a forEach the difference is the input values are modified with some business logic before they become new outputs.

live example and resources at the end of the article

try angular 2 rxjs
try angular 2 rxjs

 

//map
console.log(" ************** map() ****************");

var myValues = [8, 78, 32 ];

var newValues = myValues.map(function(value){
return value - 5;
});

console.log("New Values map()  : ", newValues);
angular 2 rxjs map
angular 2 rxjs map

 

2.filter() : now we want to do the calculation only if the value equals 78.

Filter returns true/false values.

//filter
console.log(" ************** filter() ****************");
var myValues = [8, 78, 32 ];

var newValues = myValues.filter(function(value){

return (value === 78);


}).map(function(value){
return value - 5;
});

console.log("New Values filter()  : ", newValues);

 

3.reduce() : now we want to return one value based on some calculation! The answer is reduce method.

 

//reduce
console.log(" ************** reduce() ****************");
var myValues = [8, 78, 32 ];

var newVal = myValues.map(function(value){
return value - 5;
}).reduce(function(total, value){
return total + value;
}, 0);

console.log("newVal reduce() : ", newVal);

angular 2 rxjs map filter reduce
angular 2 rxjs map filter reduce
  • We can chain the methods (map , filter , reduce) for more complex work.

 

4.forEach Example :

//forEach
console.log(" ************** forEach() ****************");
var vals = ['A', 'b', 'C', '4'];

vals.forEach(function(val){
console.log(" Val : "+val);
});
RXJS
RXJS

 

As we said before we will use RxJs Observables to deal with Data Streams in Angular 2.

rxjs-logo

A stream is a set of things! When we hear a set it comes to our mind the notion of Array!

We all know how to deal with an array: do operations on an array! Manipulate data in an array! Combine arrays to produce new arrays! … And more

live example and resources at the end of the article

angular 2 rxjs
angular 2 rxjs

 

So now imagine that a stream is an array! And we can do all the operations on this stream the same way we do on an array! Using ready to use operators

Life is easy : )

The API to deal with Streams is called Observables (use functional operators to transform streams). (like Array#extras in JavaScript : e.g. map, reduce, filter  )

Observables allow us to define a stream, subscribe to this stream and do some work with it.

Reactive Extensions for JavaScript
Reactive Extensions for JavaScript

 

RxJS is the library used by Angular 2 to deal with Observables.

Angular 2 Rxjs is: ( The Reactive Extensions for JavaScript ).

  1. Reactive programming.
angular 2 reactive programming
angular 2 reactive programming

 

 2. Treats events as a collection. (Data Stream)

3. Manipulate a set of events with “Operators” (map , filter …) #extras in JavaScript

 Things you need to know!

Functional Reactive Programming (FRP)
Functional Reactive Programming (FRP)

 

Functional Reactive Programming (FRP): is a programming style based on streams. In Functional Reactive Programming practice we build all programs using streams!

      Keep in mind that we need to subscribe to an observable in order to wake it up, once the observable is in the “wake up” mode it produces a reaction on new generated values.

 Stateless and Statefull ! What’s that! Simply
Stateless and Statefull ! What’s that! Simply

Stateless and Statefull ! What’s that! Simply

Stateless means: we don’t keep the state of component.

Statefull means: we keep the state of component.

In FRP we keep the state in the streams or in DOM (but not in application code).

In real world, applications are composed by components. Components have some states and we want to store them. We can do such thing with observables. And when we need a state all we need to do is to subscribe to this observable.

next

Observables can be Obs-HOT or Obs-COLD.

  • An observable is Obs-COLD by default.
  • When an observable is Obs-COLD we subscribe to new producer and we start to get new values. Each time we subscribe we are connected to a new producer.
  • Obs-HOT ? if we want to make our Observable Obs-HOT we need to call the shared()
  • Obs-HOT means that subscribers are served from a shared producer.

We should pay attention to the way to use observables Obs-HOT or Obs-COLD.

Compare observables and promises
Compare observables and promises
  • Promises and Observables have similar semantics
Promise Observable
x.then(valueFn,errorFn );

 

x.subscribe(valueFn,errorFn, completeFN );

call o to n times

  • Differences
Promise Observable
Cannot be cancelable

 

x.unsubscribe(  );

 

  • Create an Observable or Promise
Promise Observable
 myPromise = new Promise((resolve, reject) => {

AsyncCall()

resolve(Value)

reject(error)

});

 

 Observ = new Observalbe( observer => {

 

If(value)

{

Observer.next(value); (we can call n times)

Observer.next(value); (we can call n times)

 

Observer.complete();

(the observable can be unstoppable it never ends omit complete() )

}

Else

{

Observer.error(myError);

}

 

}

 

);

 

Observables in Angular 2
Observables in Angular 2

 

Observables in Angular 2 (made easy)

With observables helpers in angular 2 RxJS it’s easy to use.

  • of(v1, v2, v3 ….vN) : create observable from those values.
  • from(promise/iterable/observable) : it accepts a primise or an iterable or an observable from another API
  • fromEvent(item, eventName)
  • Error handling is similar to Promises (catch)

myObserv.catch( error => {

if ( error instanceof OkayError) {

return Observable.of(‘okay’);

} else {

throw error;

}   });

  • Finally : observables can be “retried

myObserv.retry(5);

myObserv.retryWhen (errors

errors.delay(2000)   );

If we have an error we can retry

An observable is : [thing1 , thing2 , ….thing3] in a an amount of time (t0 -> tn)

How it works
How it works

 

How it works:

  1. subscribe(nextHandler, errorHandler, completionhandler) :all values are pushed to the nextHandler.
  2. When we have an error it goes to
  3. If we want to know when it finishes we need to provide an completionhandler .
  4. Observable work in lazy Act only when we subscribe.
  5. We can unsubscribe from an observable.
Operators
Operators

 

Operators are methods to transform, deal and compose observables.

Operators pass each value that emit to the next operator , and then it process the next value.

Var myResult = mySource.anOperator();

  • myResult = Observable.
  • myResult subscribes to mySource !
  • then we do some business logic and emit new values.

When we unsubscribe, we do from both myResult and mySource.

 

Observable Methods
Observable Methods

example

try angular 2 rxjs 1

try angular 2 rxjs 2