【发布时间】:2021-09-09 22:07:26
【问题描述】:
我正在执行此查询以获取当前用户关注的用户的帖子[例如在社交媒体中]。但是这个查询花费了很多时间。如您所见,我还将它们转换为发布实体并为每个实体设置相应的属性,我认为这是罪魁祸首。如何优化?
我在 firestore 中对用户和帖子有不同的当前集合
suspend fun getPostsForProfile(uid: String) = withContext(Dispatchers.IO) {
safeCall {
Log.d(" basePostRepository ", " getPostsForProfile is called ")
val Currentuid = FirebaseAuth.getInstance().uid!!
// get Posts where authorUid is equal to uid
val profilePosts = posts.whereEqualTo("authorUid", uid)
.orderBy("date", Query.Direction.DESCENDING)
.get()
.await()
.toObjects(Post::class.java)
.onEach { post ->
Log.d(" basepostRepository : getPostforProfile ", post.authorUid)
val user = getUser(post.authorUid).data!!
post.authorUsername = user.type
val isLiked_init = post.likedBy.find { item -> item == Currentuid}
post.isLiked = when (isLiked_init) {
null -> false
else -> true
}
}
Resource.Success(profilePosts)
}
}
suspend fun getUser(uid: String) = withContext(Dispatchers.IO) {
safeCall {
val currentUid = FirebaseAuth.getInstance().uid!!
val user = users.document(uid).get().await().toObject(User::class.java)
?: throw IllegalStateException()
val currentUser = users.document(currentUid).get().await().toObject(User::class.java)
?: throw IllegalStateException()
val isfollowed_init = currentUser.follows.find { item -> item == uid}
user.isfollowing = when (isfollowed_init) {
null -> false
else -> true
}
Resource.Success(user)
}
}
【问题讨论】:
-
找到解决办法了吗?
-
我将 val user = getUser(post.authorUid) 移出循环,因为 post.authorUid 始终等于 uid。这有帮助。但在 getPostsforFollows() [代码未在此处上传] 我在优化方面没有运气。
标签: android firebase android-studio google-cloud-firestore