title: How to keep track of chat messages seen by user
body: <p>I am building a simple Chat App using Firebase and Ionic. I am trying to keep track of number of messages that are unread for different groups that the user is member of (like WhatsApp). </p>
  
  <p>I have the messages linked to $scope through $firebaseArray </p>
  
  <pre><code>$scope.messages = $firebaseArray(&lt;ref to message path in firebase&gt;);
  </code></pre>
  
  <p>$scope.messages is iterated over and shown in the view. When a new message arrives it automatically shows up in the group being viewed. I want to keep track of messages not viewed. I am not quite sure of the best way to keep track of which messages the user has seen. I see suggestions <a href="https://stackoverflow.com/questions/22623879/managing-unread-messages-in-firebase-chat">here</a> to keep track of timestamp when a user last visited a group but am wondering if there is a better/simpler solution to this.</p>
  
  <p>The things that come to mind that I need to do are - </p>
  
  <ol>
  <li>Setup some sort of monitoring for all groups the user is member of not just the one being viewed by the user. If user is member of 50 groups I need to monitor all 50 of them individually (wonder what, if any, performance implications that has). Here I will need to setup a child_added monitoring for each of the groups the user is member of</li>
  <li>Track timestamp for last time a user was in a group</li>
  <li>As the user switches groups, change the $firebaseArray to monitor the new group and cancel the $firebaseArray setup for the previous. Change the child_added monitoring for the new group to the group being viewed previously</li>
  <li>If the user moves to another part of the app where he is not looking at any group messages (perhaps in a setting section) then again be aware of that and monitor all groups - remove the firebeaseArray from the group last being viewed and add a child_added monitoring when user moves away</li>
  </ol>
  
  <p>If the user goes to another application and pushes the Chat application in the background then I am a little unsure of what to do</p>
  
  <ol>
  <li>How does the code determine that the group whose messages the user was looking at is no longer active and new messages coming in now need to be counted</li>
  <li>I am assuming I need to monitor for the App Pause and Resume events to address that. Is there a better way?</li>
  </ol>
  
  <p>Trying to keep my code simple but feels like monitoring for unread messages is a significant chunk of work. Thanks for any ideas or pointers to sample code or to simplify this.</p>
  
  <p>-S</p>