-1

I'm working on an Android chat application that uses Firestore for its database. I'm using Kotlin and have already implemented basic features like sending and receiving messages. Now, I'm looking to add a feature that allows users to "like" or "favorite" messages.

I want to allow showing all messages the user has liked.

However, I want to avoid consuming too many Firebase resources, specifically in terms of reads and writes.

My Current Message Model :

data class ChatMessage(
    @SerializedName(FIELD_MESSAGE_ID)
    var id: String = "",
    @SerializedName(FIELD_MESSAGE_USER_UID)
    var userUid: String = "",
    @SerializedName(FIELD_MESSAGE_TEXT)
    var text: String = "",
    @SerializedName(FIELD_MESSAGE_DATE)
    var date: Date? = null,
    @SerializedName(FIELD_MESSAGE_REPLIES_QUANTITY)
    var repliesQuantity: Int = 0,
)

Initial Thoughts Adding a List<String> field to the ChatMessage model to store the UIDs of users who have liked the message. Using FieldValue.arrayUnion() and FieldValue.arrayRemove() to add and remove likes. Issue I also want to add a tab that shows all the messages that a user has liked. If I filter messages based on user UID in the like field, it risks reading all the messages, which could be costly.

Questions

  • How can I implement this feature efficiently?
  • Is there a better way to structure my data to minimize cost?
  • What are your recommendations for cost-effective and performant implementation?

Thank you in advance for your insights!

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
Jéwôm'
  • 3,753
  • 5
  • 40
  • 73

2 Answers2

1

How can I implement this feature efficiently?

This sounds to me pretty efficient.

Is there a better way to structure my data to minimize cost?

I cannot see any other solution that can minimize the cost. Because each time a user likes or adds a message to favorites, you need to perform a write operation. That operation cannot be avoided in any way.

What are your recommendations for cost-effective and performant implementation?

You already found a working and cost-effective implementation. However, generally speaking, don't try to optimize something that actually doesn't produce any problems.

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
0

If I filter messages based on user UID in the like field, it risks reading all the messages, which could be costly.

You can receive limited the number of documents by use .limit, Also the Firestore won't charge from cached documents, see this.

flutroid
  • 1,166
  • 8
  • 24