I am building a chat app and displaying the text messages with the code below.I wanna know how i can paginate this live data that i am getting from cloud firestore so that a user can only look at the past say 30 messages using the paging 3.0 library.
ChatLogViewmodel
fun listenForMessages(user: User): LiveData<List<String>> {
val toId = user.uid
val betweenList = mutableListOf(Id(fromId), Id(toId))
val sortedList = betweenList.sortedBy { it.Id }
repository.getChatReference()?.whereEqualTo("between", sortedList)
?.addSnapshotListener { documents, e ->
if (e != null) {
return@addSnapshotListener
}
if (documents != null) {
for (document in documents) {
docId = document.id
docids.clear()
docids.add(docId)
}
}
docList.value = docids
}
return docList
}
fun listener(docId: String): LiveData<List<ChatMessage>> {
repository.getChatReference()?.document(docId)?.collection("Messages")?.orderBy(
"timestamp",
Query.Direction.ASCENDING
)?.addSnapshotListener { snap, e ->
if (e != null) {
return@addSnapshotListener
}
if (snap != null) {
messages.clear()
for (doc in snap.documents) {
val chatMessage = doc.toObject(ChatMessage::class.java)
if (chatMessage != null) {
messages.add(chatMessage)
isScrollable.value = true
}
}
}
messageList.value = messages
}
return messageList
}
ChatLogActivity
viewModel.listenForMessages(user).observe(this, {
it.forEach {doc->
viewModel.listener(doc).observe(this, { chatMessages->
binding.chatLogRecycler.adapter = ChatAdapter(chatMessages)
if (binding.chatLogRecycler.adapter!==null)
binding.chatLogRecycler.scrollToPosition(((binding.chatLogRecycler.adapter)?.itemCount!!) -1)
})
}
})
Repository
class ChatRepository @Inject constructor() {
fun getUserReference(uid:String): DocumentReference? {
return Firebase.firestore.collection("Users").document(uid)
}
fun getChatReference(): CollectionReference? {
return Firebase.firestore.collection("ChatChannels")
}
}