Firebase实时数据库addValueEventListener [英] Firebase Realtime Database addValueEventListener

查看:149
本文介绍了Firebase实时数据库addValueEventListener的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经将setPersistenceEnabled设置为true,并且正在使用addValueEventListener,并且在其中使用了onDataChange方法. 我的应用程序会在每次调用该方法时始终从服务器下载数据吗,或者我的应用程序是否会从缓存中获取数据(如果有)? 脱机时,我确定数据来自缓存.

I have set setPersistenceEnabled to true and I am using a addValueEventListener and inside that a onDataChange method. Will my app always download the data from server every time that method is called or will my app get the data from the cache if available? When I am offline I am sure that the data comes from the cache.

#askFirebase

推荐答案

当您将监听器与addValueEventListener()附加在一起并且数据在本地磁盘缓存中可用时,onDataChange()方法将立即使用来自缓存.

When you attach a listener with addValueEventListener() and the data is available in the local disk cache, the onDataChange() method will immediately fire with the data from the cache.

然后,Firebase客户端将向服务器注册以更新数据.每当收到更新的数据时,它将再次调用onDataChange().

The Firebase client will then register with the server for updates to the data. Any time it receives updated data, it will invoke onDataChange() again.

因此,如果本地磁盘缓存中有陈旧的数据,则可能会连续快速"收到两次对onDataChange()的调用:一次是使用陈旧数据,第二次是使用最新数据.当前无法查看数据是否陈旧.

So if you have stale data in your local disk cache, you may receive two calls to onDataChange() in "quick" succession: one with the stale data and the second one with the latest data. There is currently no way to see whether the data is stale or not.

这一次真正造成棘手的情况的唯一时间是您使用addListenerForSingleValueEvent().由于您只会在此获得第一个onDataChange()事件,因此您可能只会获得过时的数据.这是我们建议不要将磁盘持久性与单值事件侦听器混合使用的原因之一.

The only time when this really creates a tricky situation is when you use addListenerForSingleValueEvent(). Since you will only get the first onDataChange() event there, you may only get the stale data. This is one of the reasons that we recommend not to mix disk persistence with single-value event listeners.

这篇关于Firebase实时数据库addValueEventListener的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆