【发布时间】:2021-08-08 15:29:22
【问题描述】:
我正在尝试先获取我所有的帖子,哪个时间是较新的,我已经进行了这个查询,应该将我上传或其他人发布的所有最新帖子带给我。
问题是我收到的帖子是用时间戳打乱的,都是混在一起的,而不是按新的排序
如果我从 firebase 控制台执行相同的查询,它们会按应有的方式排序
我的recyclerview NOT 有任何 reverselayout 或 stackfromend 属性,我不希望使用它们,而是我只希望我的列表来自 firebase 排序
@ExperimentalCoroutinesApi
suspend fun getLatestPosts(): Flow<Result<List<Post>>> = callbackFlow {
val postList = mutableListOf<Post>()
// Reference to use in Firestore
var eventsCollection: CollectionReference? = null
try {
eventsCollection = firestore.collection("posts")
eventsCollection.orderBy("created_at", Query.Direction.DESCENDING)
} catch (e: Throwable) {
// If Firebase cannot be initialized, close the stream of data
// flow consumers will stop collecting and the coroutine will resume
close(e)
}
val suscription = eventsCollection?.addSnapshotListener { value, error ->
if (value == null) {
return@addSnapshotListener
}
try {
postList.clear()
for (post in value.documents) {
post.toObject(Post::class.java)?.let { fbPost ->
fbPost.apply {
created_at = post.getTimestamp(
"created_at",
DocumentSnapshot.ServerTimestampBehavior.ESTIMATE
)?.toDate()
}
postList.add(fbPost)
}
}
offer(Result.Success(postList))
} catch (e: Exception) {
close(e)
}
}
awaitClose { suscription?.remove() }
}
现在,如果我在获取有效数据后在本地对列表进行排序,但我不希望它是客户端,我希望从服务器获得一个有序列表。
我做错了什么?
帖子时间戳以 @ServerTimestamp 和日期格式保存到 Firestore 中
【问题讨论】:
标签: android firebase kotlin google-cloud-firestore