带有 Room 持久性库的 Firebase
Firebase with Room persistance library
我正在考虑使用 room 库从 Firebase 获取数据并将其存储在我的 phone 上。但是,我心里有个疑问。我想使用 Firebase ChildEventListener
因为我只想在更改或添加子项时获取数据。但是,我也知道 ChildEventListener 会在应用程序首次启动时获取所有数据。所以,my question is that in what cases firebase ChildEventListener will fetch whole data and in what cases a single child?
。实际上,知道这一点很重要,因为如果 ChildEventListener 两次获取相同的数据,room 将给出 unique id duplication 错误。
如果您无法控制 ChildEventListener 何时触发,一个简单的策略是在所有情况下都覆盖。您可以使用以下代码避免唯一 ID 重复错误:
@Insert(onConflict = OnConflictStrategy.REPLACE)
如果替换不适合你有other options.
类 实现 ChildEventListener 接口可用于接收有关给定数据库引用的子位置更改的事件。仅当您想要响应子级更改时才应使用此接口,因为此接口具有用于添加、删除、更改或移动子级时的单独方法(onChildAdded()
、onChildRemoved()
、onChildChanged()
和 onChildMoved()
)。
In what cases firebase ChildEventListener will fetch whole data and in what cases a single child?
例如,onChildAdded()
方法在您启动应用程序以从特定位置获取所有子项时调用一次,但每次在该位置添加新子项时也会调用。
您可以使用以下代码删除重复数据
@Entity(tableName = "post",indices = @Index(value = {"id"},unique = true))
在您的模型 class 中,您可以将 "id" 设置为唯一的,这样相同的数据就不会存储多次。请记住一点,不要提供唯一的主键,您必须为房间数据库提供单独的 ID。希望对你有帮助:)
我正在考虑使用 room 库从 Firebase 获取数据并将其存储在我的 phone 上。但是,我心里有个疑问。我想使用 Firebase ChildEventListener
因为我只想在更改或添加子项时获取数据。但是,我也知道 ChildEventListener 会在应用程序首次启动时获取所有数据。所以,my question is that in what cases firebase ChildEventListener will fetch whole data and in what cases a single child?
。实际上,知道这一点很重要,因为如果 ChildEventListener 两次获取相同的数据,room 将给出 unique id duplication 错误。
如果您无法控制 ChildEventListener 何时触发,一个简单的策略是在所有情况下都覆盖。您可以使用以下代码避免唯一 ID 重复错误:
@Insert(onConflict = OnConflictStrategy.REPLACE)
如果替换不适合你有other options.
类 实现 ChildEventListener 接口可用于接收有关给定数据库引用的子位置更改的事件。仅当您想要响应子级更改时才应使用此接口,因为此接口具有用于添加、删除、更改或移动子级时的单独方法(onChildAdded()
、onChildRemoved()
、onChildChanged()
和 onChildMoved()
)。
In what cases firebase ChildEventListener will fetch whole data and in what cases a single child?
例如,onChildAdded()
方法在您启动应用程序以从特定位置获取所有子项时调用一次,但每次在该位置添加新子项时也会调用。
您可以使用以下代码删除重复数据
@Entity(tableName = "post",indices = @Index(value = {"id"},unique = true))
在您的模型 class 中,您可以将 "id" 设置为唯一的,这样相同的数据就不会存储多次。请记住一点,不要提供唯一的主键,您必须为房间数据库提供单独的 ID。希望对你有帮助:)