WhatsApp Clone — Jetpack Compose — Chat
Let’s connect users to one another.
There are 2 scenarios whenever a chat details page is opened,
- New conversation
- Continue conversation
Let’s take this one by one.
New conversation
After opening the chat details page, which is ChatUserView, a check is made to the Firestore for the availability of the chat. In FirestoreUtility, we start a check from chats collection.
If currentTask doesn’t exist we call the isFalse() method from the callback, and update the UI.
Above image shows how the conversation will start. So, if the user wants to connect with the user a 👋 message will be sent first.
The above image shows what will happen when the Send Hi!! 👋 is clicked. Now let’s check our Firestore. It will help in understand how we are maintaining the database for the chat.
A chats collection is created which will hold all the chats made by the users. Whenever a chat is created, there will be 2 documents created for each user (Id will be the user id given by Firebase at the time of authentication). And each document will have again a chats collection. So whenever there is a new message then for each user document the message will be added.
For user chats collection we will have the to-user id as a document, that way other user document will also be added in the same collection and there will be no duplicates chat. So for checking if the conversation already available we simply have to check if chats->currentUserId->chats->toUserId is available or not.
We will be saving few details related the conversation, like when and by whom it was created, is it a group, is it a favourite chat for the user, last message details and the list of members in the chat.
And it will also have a messages collection which will store all the messages created between currentUser and toUser.
This is how the chat database looks like in the Firestore. One drawback this approach has it that, there will be two writes for each message. But on the other hand it would be easy to update the details of the chats for each user separately.
Continue Conversation
If the conversation has already started the UI will look like
And each message will be stored the same way as mentioned above.
One more option in the chat is to make any conversation as favourite. So at the top bar an option to mark the chat as favourite is given.
If it is marked as favourite, then in the DB for the current user chatIsFavourite key will be true.
To know all the logic put behind the send message and receive message, can check ChatUserViewModel and FirestoreUtility.
Now let’s check the list of chat the current user is having. For that go to the next article which is WhatsApp Clone — Jetpack Compose — Chats.