Search code examples
androidfirebasefirebase-realtime-databasestructure

Firebase realtime database structure in chat app


sorry for my bad English level, I'm from Argentina.

I have the following messages data structure in Firebase:

"messages"
   "-KezmqXSdKCNFFA432Uc___-KfCEwklG_y3naRDIUiY"
         "messageDate": "20170620"
         "messageTime": "18:44" 
         "message": "Hi"
   "-KezFDSAADFASFFS3221___-KASDF32324SDFASD1FS"
         "messageDate": "20170620"
         "messageTime": "22:23" 
         "message": "How are you?"

Where -KezmqXSdKCNFFA432Uc, -KfCEwklG_y3naRDIUiY, -KezFDSAADFASFFS3221 and -KASDF32324SDFASD1FS are users.

My problem is that I created a childEventListener in "messages" node to receive new users messages but I am receiving all the new messages of all the users (I'm logged in one user per app) because my childListener is in "messages" node.

Is it correct that if I have 1000 users when adding a message, a new message reaches the 1000 users? (Assuming that within the app, you can check to which user that message belongs).

Thanks!


Solution

  • If you do a structure like similar to this:

    -chats
       - chatUID
           - members
               - userUID
           - lastMessageSent:messageUID
           - ... more properties  
    
    -chatMessages
       - chatUID
         - messageUID
             - sentBy: userUID
             - messageDate:""
             - messageTime:""
             - message:""
    
    -userChats
        - userUID
           - chatUID
    

    you can attach a listener to /userChats/userUID, which will display active chats, and a listener to /chatMessages/chatUID, which will get all chat messages for a specific chat conversation.

    This way is a lot easier to setup firebase security rules, and users will only receive chat messages which they are apart of.