Tuesday, October 20, 2015

Observer pattern in AngularJS

I have implemented Observer pattern to solve an issue that I was facing in my project. This post is regarding my implementation.

In my current project, when there is a change in URL, the controller will call angular service to get the data from server. But during the start of the application, URL redirect happens multiple times, which makes the controller to call the service multiple times.

I tried many options to prevent it from controller itself (from where it is getting called); but that made my code ugly and complex.

So I left the controller as it is and tried to implement my logic in angular service. I decided to use observers to prevent multiple calls to the server.
Have a look at the example in plunker (http://plnkr.co/edit/IBK7xX?p=preview)

The basic design of the example application is,
- It has an angular service, which makes request to server and gets the data (services.js - myService)
- It has a controller, which calls angular service to get the data and bind to the view (script.js - MyController)
- It has a html view, which bind with the controller (index.html)

To simulate the issue, I will call the service inside a for-loop from my controller. The loop will call the function 3 times. Without observers, the service hits the server 3 times and gets the response. Below is the console from Firebug.
This example gets the latitude and longitude of given location using Google api.

Our ultimate aim is to decrease the number of request to server; the immediate thing comes into our mind is Cache. But Cache will not help here, as all the requests are hitting the server at the same time.

The next option is Observer pattern.
I have created a local variable "observers" (array) in services.js. Whenever the service get multiple requests, the service will send only one request to server and add the references of all other requests to the observers array (have a look at services.js file). When the service receive response from the server, it will also send the response to all the observers who requested the same data and remove its reference from the observers array.

Click "Send Multiple Request" in the example and check the console in Firebug or Networks tab in Chrome. You will see 3 requests.


Click "Send Multiple Request With Observer" in the example and check the console in Firebug or Networks tab in Chrome. You will see only one request sent to server. But all the 3 requests are resolved properly once the response is received.

One more example is here (http://plnkr.co/edit/xzUV2U?p=preview) which supports multiple functions in the service.

-Jeyabalaji

3 comments:

  1. Wow what a man��������

    ReplyDelete
  2. Wow!.. super topic!.. Mathathu onume purila!.

    ReplyDelete
  3. @Dinesh, Bharathi: ellam thangalidam kuditha Gnanapal manna..

    ReplyDelete