如何在Android中取消Firebase实时数据库正在进行的写入或删除操作

huangapple go评论68阅读模式
英文:

How to cancel Firebase Realtime Database ongoing write or delete operation in Android

问题

我正在开发一个聊天应用,就像 WhatsApp 一样,我需要为用户提供在没有网络连接时将他们的消息保存为未发送状态的功能,一旦网络恢复,那些数据就应该会被重新尝试发送给接收者。

但是,如果我使用 Firebase 的 .setValue() 来安排写入操作,那么如果用户改变主意,不想要发送那条消息,或者在技术术语中不想要执行 setValue(),我该如何取消该过程呢?如何中止正在进行的写入操作呢?

英文:

I am building a chat app, and like Whatsapp, I need to provide users the facility to save their messages as undelivered when internet connectivity is OFF, and as soon as the internet is back then that data should be retried to be sent to the receiver.

But, in case I scheduled a write operation using Firebase .setValue(), then how could I cancel that process in case the user changes his mind and doesn't want that message to be sent, or in technical terms does not want to setValue(), how could I stop that ongoing write.

答案1

得分: 1

根据您的情况,问题出现在设备离线时,您希望让用户有可能删除消息,以便在设备恢复连接后不再显示。由于setValue()方法返回一个Task<Void>对象,并且因为我在这个类中没有看到任何取消方法,唯一要做的就是简单地删除消息。在这种情况下,当用户重新上线时,其他用户将看不到已删除的消息。

另一方面,确实存在用户发送消息,然后立即失去连接的可能性。即使有一个取消方法,您也无法取消任何操作,因为消息已经设置在服务器上。同样,您唯一的选择是删除消息。删除操作将保留在队列中,直到设备恢复连接并在同步后立即删除消息。

此外,请记住启用持久性,因为默认情况下它是禁用的:

setPersistenceEnabled(true);
英文:

As I understand from your scenario, the problem arises when the device is offline and you want to let the user the possibility to delete the message, so it cannot be displayed once it regains connectivity. Because the setValue() method returns a Task<Void> object and because I don't see any cancel method in this class, the only thing to do it to simply remove the message. In this case, when the user is back online, no other users will see the deleted message.

On the other side, it's true that there is a chance in which the user sends the message and right after that he loses connectivity. Even if there was a cancel method, you would have nothing to cancel, as the message is already set on the server. Again, the single option that you have is to delete the message. The delete operation will remain in queue until the device regains connectivity and right after the synchronization the message will be deleted.

Besides that, remember to set the persistence enabled, because it's not enabled by default:

setPersistenceEnabled(true);

huangapple
  • 本文由 发表于 2020年10月17日 17:51:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/64401155.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定