I've Room Entity called `Post`, and it has propert...
# android
r
I've Room Entity called
Post
, and it has property called
isLiked
. I want to retrieve its value in repository class to determine whether to like or unlike a post. I'm using below code but app automatically crash with
I/Process: Sending signal. PID: 12911 SIG: 9
when using below code block. what am i doing wrong?
Copy code
@Query("SELECT * FROM posts WHERE postId = :postId")
fun isPostLiked(postId: Long): Post
Copy code
suspend fun toggleLike(postId: Long) {
    Log.d(TAG, "inside toggle like")
    if (db.postDao.isPostLiked(postId = postId).isLiked == true) {
        Log.d(TAG, "unlike post")
    } else {
         Log.d(TAG, "like post")
    }
}
j
Can you limit to 1?
Copy code
@Query("SELECT * FROM posts WHERE postId = :postId LIMIT 1")
r
not working
can i use retrieved room entity in repository to decide further logic? or i must have to use it on UI thread?
i
Make your method a
suspend fun
and it'll run on the right background thread automatically
r
Hi @Ian Lake, tried that one but still app crash
Copy code
@Query("SELECT * FROM posts WHERE postId = :postId LIMIT 1")
suspend fun isPostLiked(postId: Long): Post

suspend fun toggleLike(postId: Long) {
        Log.d(TAG, "this will be printed")
        db.postDao.isPostLiked(postId).isLiked?.let {
            if (it) {
                Log.d(TAG, "post already liked, its not working")
            } else {
                Log.d(TAG, "post not liked, its not working")
            }
        }
}
Even, update query is not updating db
Copy code
@Query("UPDATE posts SET isLiked = 1, likesCount = likesCount + 1 WHERE postId = :postId")
suspend fun likePost(postId: Long)
@Ian Lake its working now, thanks. reason of app crash was, item was not found in db.
šŸŽ‰ 2