show message not sent when device is offline and show message is sent when device comes online firebase firestore

Viewed 186

The app is for messaging, Firebase Firestore used I want to notify user if message is sent to server or not. To do this i added "sent (Boolean)" property to message entity , it works fine when i send message as (sent = false)

val messageToSend = TextMessage(editText_message.text.toString(), Calendar.getInstance().time,
                            FirebaseAuth.getInstance().currentUser!!.uid,
                            otherUserId, currentUser.name, false, null, false)
            editText_message.setText("")
            sendMessage(messageToSend, channelId)


fun sendMessage(message: TextMessage, channelId: String) {

    FirebaseConstants.chatChannelsCollectionRef.document(channelId)
            .collection("messages")
            .add(message).addOnSuccessListener {
                it.update(mapOf("sent" to true))
            }
}

and i control it in my view holder

  if (!message.sent) {
            viewHolder.text_message_status_indicator.background = ContextCompat.getDrawable(context, R.drawable.ic_baseline_access_time_24)
        }

The problem is when device is online again the message property is not updated (including sent = true)

Please help me with that problem

1 Answers

To detect whether a message is coming from the local cache, or from the database on the server, you're better of using DocumentSnapshot.getMetadata().hasPendingWrites(). If this property is true, the data isn't written to the server yet. If it is false, the data has been committed to the server.

For an example of this, see the Firestore documentation on events for local changes.

Related