Eddie Lee Eddie Lee - 5 days ago 5
Android Question

How to add a timestamp for when the Firebase object/node+subtree was modified?

I'm looking to create a field for storing the timestamp of when the object was last changed. So if any of the object's properties (aka subtree) is modified, be able to set a timestamp field to the current time.

Firebase doesn't seem to have a way to keep track of when an object was last updated. Has anyone actually implemented a way to do this in an elegant fashion?

Jay Jay
Answer

You can easily keep track of when a node was modified

root
  users
    some user stuff
  messages
    some messages
  places_to_eat
    some places to eat
  timestamps
    users: a timestamp
    messages: a timestamp
    places_to_eat: a timestamp

when data is written to the users node, update the timestamps node:

// iOS / ObjectiveC

Firebase *usersTimeStampsRef = [timeStampsRef childByAppendingValue:"users"];

[usersTimeStampsRef setValue:kFirebaseServerValueTimestamp];


// Android / Java

Firebase usersTimeStampsRef = usersTimeStampsRef.child("users");

usersTimeStampsRef.setValue(ServerValue.TIMESTAMP);

(you could just use timestamps/users as well)

Or, getting fancy, keep the timestamp within the node itself

root
   users
     timestamp: a timestamp
     user_list
       user_1
       user_2

I have a number of ObjC objects that are class objects to handle reading and writing of data and they automatically update the timestamp when modified.

So for example, I have a users class.

User aUser = [UserClass new]
[aUser createUser:"Jay"]

when the createUser method is called, inside the class it sets up the user and writes out the userName and updates the timeStamp accordingly. It's pretty seamless and low maintenance.

Actually, the parent class I created does the heavy lifting and writing of the timestamp so all of the subclasses that interact with Firebase inherit that functionality.

Comments