Search code examples
angularjssocket.ioreal-time

Real time update with Angular and Socket


I have a problem with my current implementation of real time with Angular and Socket.io.

  • I have a model in Angular and I watch it for modification with $scope.$watch().
  • When I detect a modification I send a message with socket to my server.
  • When my server detect a call on this update, I save the modification and I send to other user the modification
  • Other users are notified about someone modification.

But, I have a problem with this implementation :

  • User A update a field
  • Send message to server
  • Save to the server
  • Update notification send to users
  • User B is notified
  • User B model is updated
  • The watch detect a modification in model of User B and send notification
  • Send message to server
  • Save to the server
  • etc...

So, my question is, how to avoid this infinite loop and infinite update ?


Solution

  • You could define on the client side a variable named changed_elsewhere. The default value of changed_elsewhere it's false.

    When you receive on your socket a new value from the server, then set changed_elsewhere to true. Then, on the watcher, send the new changed value to the server only if changed_elsewhere is false. If changed_elsewhere is true, then you know that the value has already been on the server and you don't need to send it again.

    Finally, your watcher should look this way: if changed_elsewhere is true, then turn changed_elsewhere to false and don't do nothing; if changed_elsewhere is false, then send the new value to the server.

    Sorry if the changed_elsewhere name is not very suggestive, but i hope that you get my idea.