Skip to content

Instantly share code, notes, and snippets.

@lukaspili
Created Aug 1, 2017
Embed
What would you like to do?
override fun queryPosts(tab: FeedTabController.Tab): Observable<List<Post>> {
val postsQuery = ParseQuery.getQuery<ParseObject>("Post")
.whereExists("createdAt")
.whereExists("building")
.whereExists("author")
.include("building")
.include("photo")
.include("author")
.include("author.Picture")
.whereEqualTo("building", ParseObject.createWithoutData("Building", sessionManager.buildingId))
.setLimit(QUERY_LIMIT)
.setCachePolicy(ParseQuery.CachePolicy.NETWORK_ELSE_CACHE)
when (tab) {
FeedTabController.Tab.AllPosts -> {
postsQuery.whereEqualTo("category", "community")
}
FeedTabController.Tab.TenantPosts -> {
postsQuery
.whereDoesNotExist("stickyUntil")
.whereEqualTo("category", "community")
.whereMatchesQuery("author", ParseUser.getQuery().whereNotEqualTo("AccessLevel", "Manager"))
}
FeedTabController.Tab.ManagerPosts -> {
postsQuery
.whereEqualTo("category", "community")
.whereMatchesQuery("author", ParseUser.getQuery().whereEqualTo("AccessLevel", "Manager"))
}
FeedTabController.Tab.FeedbackPosts -> {
postsQuery.whereContainedIn("category", listOf("issue", "compliment"))
if (!sessionManager.isManager) {
postsQuery.whereEqualTo("author", ParseUser.getCurrentUser())
}
}
}
val now = Date()
return ParseObservable.find(postsQuery)
.toList()
.flatMap { posts ->
if (posts.isEmpty()) {
return@flatMap Observable.empty<Triple<List<ParseObject>, List<ParseObject>, List<ParseObject>>>()
}
val likesQueries = ArrayList<ParseQuery<ParseObject>>()
val commentsQueries = ArrayList<ParseQuery<ParseObject>>()
posts.forEach {
likesQueries.add(ParseQuery.getQuery<ParseObject>("Like")
.whereEqualTo("post", it))
commentsQueries.add(ParseQuery.getQuery<ParseObject>("Reply")
.whereEqualTo("post", it))
}
return@flatMap Observable.zip(
ParseObservable.find(ParseQuery.or(likesQueries)).toList(),
ParseObservable.find(ParseQuery.or(commentsQueries)).toList(),
{ likes, comments -> Triple(posts, likes, comments) })
}
.map { (posts, likes, comments) ->
posts.map { post ->
val postLikes = likes.filter { it.getParseObject("post").objectId == post.objectId }
val isLiked = postLikes.count { it.getParseObject("user").objectId == sessionManager.userId } > 0
val postComments = comments.filter { it.getParseObject("post").objectId == post.objectId }
val isCommented = postComments.count { it.getParseObject("author").objectId == sessionManager.userId } > 0
ParseConverter.convertToPost(post, now, postLikes.size, isLiked, postComments.size, isCommented)
}
}
.map { it.sortedWith(compareByDescending(Post::isSticky).thenByDescending(Post::createdAt)) }
.doOnNext { Timber.d("query posts success: ${it.size}") }
.doOnError { Timber.e(it, "query posts failure") }
.defaultIfEmpty(emptyList())
.observeOn(AndroidSchedulers.mainThread())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment