Ngrx: Redux in Angular (5 min read)

in #technology7 years ago

Screen Shot 2018-01-04 at 18.36.54.png

Ngrx is a library that adds redux patterns with Inbuilt Rxjs support to Angular. We will come back to redux in a min, let's talk about what is Rxjs and what can it do.

Screen Shot 2018-01-04 at 18.37.13.png

Rxjs is an implementation of ReactiveX framework for javascript and stands for "Reactive extensions for javascript", Originally ReactiveX was created for .NET framework by a computer scientist at microsoft named Eric Meijer. Later it was ported to Java and named RxJava by the people at Netflix, and then to Rxjs by Matthew Podwysocki, Bart de Smet and Erik Meijer.

Observables:
Reactive extensions was originally developed to solve problems across asynchronous and event based programming with the help of Observables. Asynchronous in the sense that the availability of state change is not predictable or it does not happen in regular intervals. So what are observables? the observables pattern was developed by combining two other software design patterns namely observer and Iterator pattern.

The observer pattern consists of an object that has a list of its dependents and every time there is a state change on the object it alerts the dependents about the change. Usually the dependents expose a method out that the object can call in for communicating alerts. Objects in the pattern are generally known as Subjects and the dependents as Observers (hence the name Observer Pattern). Iterator pattern is similar to the foreach loop where the iterator goes over individual items in a container (generally collection) and once the iterator completes going over all the elements its returns or if there is an error during the process it throws the error.

Reactive extensions pick up the concepts of observer and iterator pattern and combines it into one which makes it behave like an observer pattern that not only allows the notifications to observers when the state changes at source but also when its done communicating all the state changes and in case there was an error at the source. Notifications are usually communicated by invoking the next method on the observer for state change, OnCompleted method when its done communicating all the changes and OnError method if there was an error during the process at source.

Observables have a few other overrides like subject and BehaviorSubject. Subject inherits from Observable but additionally allows the object to invoke the next method on the observer to pass or emit custom values and the BehaviourSubject inherits from Subject and additionally allows the observer to be set to a default value to begin with.

Operators:

There are many operators that Rxjs offers some of the regularly used ones are:

  1. map : Used to transform an object
  2. mergeMap: For combining and emitting values from outer observable with inner observables
  3. switchMap: To Switch the context from outer observable to inner, and to only emit inner observable values
  4. debounceTime: ignores emitted values until specified time, usually for controlling user input, the the wait time starts after the user stops
    typing and after the wait period it starts emitting the last value.
  5. debounce: Similar to Debounce time, but generally used in variable wait time scenarios
  6. distinctUntilChanged: Only emits if the current value is different from the last emitted value
    Refer to https://www.learnrxjs.io/ the complete list. One thing to keep in mind is that all the operators respect immutability of the observables, i.e if the the observed values are morphed they do not cause the source state to change.

Screen Shot 2018-01-04 at 18.37.34.png

Redux:
Redux is a very popular framework for managing the state of our applications. It is based on the single source of truth concept. Traditionally the applications were created with multiple components for a screen and the data exchange between the components was two dimensional. So the data flew from either parent to the child component or the other way around. and when there was a requirement for a sibling component to receive the same data there was this whole data then passed up from child to the parent and down again to the sibling, Soon as the components grew the data communication between them got worse to maintain leading to something popularly known as the spaghetti code and it became harder to maintain consistent state of data between multiple components.

Screen Shot 2018-01-04 at 18.37.47.png

Redux is best known to solve the exact same problem mentioned above. It consists of a single store that persists the entire state of the application. The store emits an observable and all the components that require data subscribe to the store and as we know from above description about observables, every time there is a state change in the store all the subscribed components are notified of the change resulting in consistent data throughout all the components. And when a component requires to change the state of data they make use of pure functional way and it dispatches a action that is processed by a reducer, The reducer then either clones or creates a completely new state leaving the current state un-altered, and stores the new state in the store. Due to the pure functional way of passing around data there are no side effects that can unpredictably change the state. But, this also means the communication with external resources is also restricted. For this purpose Ngrx provides Effects that can be used to manage the side effects that are required to communicate with the external world.

Screen Shot 2017-11-24 at 04.36.35.png

The actions are registered in effects modules to be watched and based on the type of the actions external resource communications are performed. When an action is dispatched from a component it invokes the effect and as soon as the data is received from external resources a new action is dispatched from effects for the reducer to process the data and persist it in store. Individual components subscribe to the store and request for specific pieces of data relevant to the components. Since the subscriptions are observable based every time when there is a state change at the store the updated state gets pushed to all the subscribed components.

Sources:

  1. www.udemy.com/the-complete-guide-to-angular-2/learn/v4/overview --Maximilian Schwarzmüller
  2. www.udemy.com/the-complete-angular-master-class/learn/v4/overview --Mosh Hamedani
  3. www.youtube.com/watch?v=f97ICOaekNU--Angular Firebase
  4. pluralsight --Duncan Hunter
  5. www.learnrxjs.io --Community (people like you and me)

Please correct me in comments if I have missed something, Thanks


Let's share knowledge and build awesome products that we can be proud of!

Sort:  

Congratulations @rakeshd! You received a personal award!

1 Year on Steemit

Click here to view your Board

Support SteemitBoard's project! Vote for its witness and get one more award!

Congratulations @rakeshd! You received a personal award!

Happy Birthday! - You are on the Steem blockchain for 2 years!

You can view your badges on your Steem Board and compare to others on the Steem Ranking

Vote for @Steemitboard as a witness to get one more award and increased upvotes!