ListenerRegistration
represents a subscription of sorts, for a database reference,
when you attach a listener to the reference. You'll use it to assign a
posts
listener to
it and to remove it when needed, to clean up your code, and
to stop receiving
changes.
Next, navigate to
listenForPostsValueChanges()
. Replace the
TODO
inside the
fuction with the following implementation:
private
fun
listenForPostsValueChanges
()
{
// 1
postsRegistration = database.collection(POSTS_COLLECTION)
// 2
// 3
.addSnapshotListener(EventListener
{ value,
error ->
// 4
if
(error !=
null
|| value ==
null
) {
return
@EventListener
}
// 5
if
(value.isEmpty) {
// 6
postsValues.postValue(emptyList())
}
else
{
// 7
val
posts = ArrayList
()
// 8
for
(doc
in
value) {
// 9
val
post = doc.toObject(Post::
class
.
java
)
posts.add(post)
}
// 10
postsValues.postValue(posts)
}
})
}
1. You assign the listener to
postsRegistration
, by attaching an
EventListener
to the database collection.
2. You receive the database collection by calling
database.collection(POSTS_COLLECTION)
.
3. You call
addSnapshotListener()
on the collection reference which starts
listening for the data changes at its location.
4. When
onEvent()
is called you first check if an error occurred by checking if the
error argument
is not
null
, or if the value
is
null
. If it is you'll just return from
Saving Data on Android
Chapter 18: Reading Data from Cloud Firestore
raywenderlich.com
262
the function, since you cannot consume the event.
5. Check if the received data actually contains documents - it isn't empty.
6. If the value is empty, it means no posts are available, and
you simply
communicate it by updating the
postsValues
with an
emptyList()
.
7. If there are values, instantiate an
ArrayList
to store them.
8. Iterate through each document in the value snapshot.
9. Parse each document as a
Post
, and add it to
posts
.
10. Update the
postsValues
with parsed posts.
To read the data, you pass
in the listener of type
EventListener
that will be called
whenever data changes or if an error occurs.
EventListener
is a generic interface
that is used for any type of event listening, and contains only the
onEvent(T value,
FirebaseFirestoreException error)
function that you're required to implement.
onEvent()
will be called with the new value or the error if an error occurred. You get
the result data as a
QuerySnapshot
object. This is the
easiest way to communicate
data changes or errors, and since it's
generic
, it can work for any collection.
Open
HomeActivity
and navigate to the
listenForPostsUpdates
function. Replace
the
TODO
inside the function with the following:
private
fun
listenForPostsUpdates
()
{
cloudFirestoreManager.onPostsValuesChange()
.observe(
this
, Observer(::onPostsUpdate))
}
When new data is received you'll reflect that, by displaying it on the screen.
You also need to remove the listener when you no longer want to receive data
change events. To do that, open
Do'stlaringiz bilan baham: