I have a collection of 10 items. I have an MVI pattern. When presenter receives event to load more data I pass over the last item visible to for the api so he knows where to start from. My api call looks accordingly:
override fun getItems(
size: Long,
from: Item?
): Single<List<Item>> =
getDocumentSnapshot("items", from?.id)
.flatMap { getItemsData(siz, it) }
.onErrorResumeNext { getItemsData(size, null) }
getDocumentSnapshot
returns the DocumentSnapshot for the last item. (I don't want to keep global/class reference of the last item). If from == null
that means its the first page and there is no previous last item. So the Rx operators execute accordingly. Thos boils down the main part where I am trying to paginate data getItemsData
:
private fun getItemsData(
size: Long,
from: DocumentSnapshot?
): Single<List<Item>> =
Single.create { emitter ->
collectionReference("items")
.orderBy("created")
.startAfter(from)
.limit(size)
.get()
.addOnCompleteListener { task ->
if (task.isSuccessful && task.result != null)
emitter.onSuccess(task.result!!.documents.map { snapshot ->
try {
snapshot.toObject(PojoItem::class.java)!!.toData()
} catch (ne: NullPointerException) {
throw DocumentParseException(ne, snapshot.id)
}
})
else
emitter.onError(NoDocumentException(cause = task.exception))
}
}
The weird thing is, that I am not getting any results when pass DocumentSnapshot
to the query. If I use certain value, in eg pass in TimeStamp
when I order by created
then it works as expected. I have debugged the code as much as I can, and I am receiving the snapshot no problemo. Did a workaround and created a global var
variable to store the last document snapshot in when receiving results lastVisible = task.result.documents.last()
but I reproduced the exact same result with it, 0 results.
NOTE: If I pass startAfter(null)
it starts from the beginning, the nullable is meant to be.