I´m using Firebase to get a list of messages. The problem is that I only need to see messages sent after I opened the page. Basically I don´t need to store the messages in the d
I don't recommend to delete the old messages, instead of it makes every user take care of reading only what is new.
If your data structure about the messages is working then you only need to add 1 attribute to your model. Each time a message is sent add the timestamp to it in an attribute.
Here is the doc how to use the ServerValue.TIMESTAMP.
Now every message node can be ordered by the timestamp.
"messages": {
"chat_1": {
"push_key_usually":{
"message": "hello",
"owner": "maybe the UID or the email",
"chat_key": "chat_1",
"key": "push_key_usually",
"timestamp": 981212312
}
}
}
To complete this, you need to make every user set its own timestamp when they load the chat. This way you can fetch that value from the database and order your message using that timestamp. The complete order is to query the value first if it is null then is the first time, simply ask for every message or work using a custom timestamp (can be zero or current time minus some minutes) and set the value. If it is not null, then use that value for your query and after you get it, set the timestamp again.
"connections": {
"user_UID": 12312412
}
Now you can do something like this:
reference.child("messages/chat_1/push_key_usuarlly").orderByChild("timestamp").startAt(yourTimeStamp).once...
The Firebase Database is not a message-passing mechanism, it is a state synchronization mechanism. If you want you can emulate a message passing mechanism on the database, but you'll have to do the work for that.
One way to accomplish this is to write the message for each device that you want to send it to. That means that every device can simply delete each message that it reads and your database will never be bigger than the total number of unread message-devices.
Another way is to store each message only once, but then track what devices have read it. Once every device has read it, you can delete the message. You'll need to store the "what devices have read each message" and the "list of all devices" in the database. This approach may require less storage, but it will definitely be more complex in code.