Ads Top

The Observer Pattern In Javascript as Implemented By Redux

Whats is a Design Pattern?
In software development, a design pattern is a reusable solution to common problems. Think of them as commonly accepted patterns to solve similar problems. There are four main types of design patterns.

These include:
Creational Patterns: These patterns deal with object creation mechanisms. How we create objects. (wiki)
Structural Patterns: Ease the design by identifying a simple way to realize relationships between entities. (wiki)
Behavioral Patterns: Identify common communication patterns between objects and realize these patterns. (wiki)
Concurrency Patterns: Deal with the multi-threaded programming paradigm. (wiki)

As a developer, day to day, you will probably not be faced with implementing most of these (at least not knowingly). However, there are times where you may find use for them. Also, there are times where you may be working on a codebase that has a common design pattern implemented. So knowledge of what the author implemented and why may be extremely helpful in that instance.

Beyond implementing these patterns yourself, a good reason to learn them is the fact that a lot of tools you may be using are probably using at least one (many times more) of these patterns. One of these patterns that many React developers use is the Observer Pattern.

What is the Observer Pattern?
The observer pattern, also referred to as the publish/subscribe pattern, is a design pattern where an object (called the subject or observable), will maintain a list of "dependents" called observers. Upon a state change, this subject will notify any of the observers automatically. An Observer is a one-to-many type of dependency between objects. That means, there is one observer that could have many subscribers.

This subject usually has three methods. One method to register an observer. One to remove an observer. And finally, one that will notify the list of subscribers of the change.

This really simplifies situations where a function or class needs to keep track of something, or better yet, know when something has happened (changed). You have two choices in this situation.

Choice 1
Polling: Polling is simple "pinging" the subject over and over asking for a change. The issue with this is you would have to constantly keep polling to keep your app up to date. What is the frequency in which you would do this? It can become very messy, very fast.

Choice 2
Push: This is the main function of the observer. Push "changes" to all the dependents observing

To explain this in greater detail, I recommend this video. Its almost 50 minutes long but if you speed it up to 1.5x or 2x you can finish it in just about half that time. It is worth it if you are interested in going deeper into the explanation. This video is a good summary of the Observer pattern chapter in the book Head First Design Patterns book.



Redux: A use case for the observer pattern
If you work in the world of React, you have probably dealt with Redux to manage the state of your application.

If you haven't worked with Redux, or do not know what it is, you can start with the Official docs. If you are like me and don't always feel like reading, there are plenty of youtube videos explaining what it is.

Redux is an implementation of the observer pattern. The redux store itself is more specific as to how this is done. A store holds the whole state tree of your application. If you want to change the state within the store, you need to dispatch an action on it.

The redux store is actually a very small library (as far as code size) for what it gives you. The store itself is simply an object that has some methods on it. These methods include getState(), dispatch(action), and subscribe(listener). replaceReducer(nextReducer) is another method but not important for this discussion. The following code is a "replica" of creating a redux store. (source fullstackreact)


This is a basic react setup where there is a class called Messages that renders a simple chat/messaging app. Within that component, there is a lifecycle method componentDidMount(). This will get called right after the component renders. What it is doing is subscribing to the store. It calls store.subscribe() in order to do this.

What is store.subscribe()? It is where we initialize the store by calling the createStore() function. createStore() is the "subject". When we call this function you will notice that it takes two arguments. The first argument is reducer, the second is initialState.

reducer is actually the reducer function declared above the Messages component and it contains all of the action types.

Within createStore we are doing a few things related to the observer pattern. The first thing is creating an empty array of listeners.
const listeners = [];
This is what we will use to store listeners/subscribers.

Next there is a subscribe method. This method "pushes" new subscribers to the array
const subscribe = (listener) => (
    listeners.push(listener)
);

Remember that subscribe is called in the componentDidMount method which fires immediately after the component mounts.

The next piece is the dispatch() method. Take a look at the following bits of code here


This is another component called "MessageInput' that is called from within the main Messages component. Its function would be to simply enter a new message to send.

The key piece of this component for this subject is the store.dispatch call. dispatch() takes an action. We then set the state equal to the reducer() function that will update all of the reducers and finally call each listener to notify them of the state change.

If that is too much to handle, hopefully this diagram provides a simple summary.

Like this post? Follow me @ _thedevnotebook on twitter

3 comments:


  1. It's interesting that many of the bloggers to helped clarify a few things for me as well as giving.Most of ideas can be nice content.The people to give them a good shake to get your point and across the command.
    Front end development course in chennai

    ReplyDelete
  2. Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a Front end developer learn from Javascript Training in Chennai . or learn thru Javascript Training in Chennai. Nowadays JavaScript has tons of job opportunities on various vertical industry. JavaScript Training in Chennai

    ReplyDelete
  3. I admire this article for the well-researched content and excellent wording. I got so involved in this material that I couldn’t stop reading. I am impressed with your work and skill. Thank you so much.
    WordPress development company in Chennai

    ReplyDelete

Powered by Blogger.