Tom11
Tom11

Reputation: 2527

Modify LiveData item fetched from Room

I have simple RecyclerView, which I fill with LiveData.

Activity:

viewModel.getBooks().observe(this, books -> booksAdapter.setBooks(books)); 

ViewModel:

public LiveData<List<Book>> getBooks() {
    books = booksRepository.getBooks();
    return books;
}

BooksRepository just calls this DAO's method:

@Query("SELECT * FROM books")
LiveData<List<Book>> getBooks();

Everything works as expected. However, in RecyclerView, I have LIKE button for every item, and I want to create onClick listener, which changes book's flag FAVOURITE accordingly. However, Room does not support that with LiveData, and it does not support MutableLiveData as well. One (not good) solution would be to send Application to adapter, where I would create repository and update Book entity "manually". But I know it is not a good idea to send Application to adapter.

Any idea how to make this? I just need to set one simple boolean column in Book entity. Thanks.

Upvotes: 1

Views: 66

Answers (1)

AzraelPwnz
AzraelPwnz

Reputation: 506

Updating a value within a livedata set will not update the underlying source. I would recommend updating your DAO to where when the user clicks the LIKE button, it updates the DB..which then in turn post an update to your livedata and the changes would be reflected on the view.

eg:

@Query("UPDATE books SET FAVOURITE = :value WHERE books.bookId = :bookId")
public abstract void setBookFavourited(boolean value, int bookId);

Also to note, you shouldnt need to pass Application to the adapter. Setup an interface within the adapter that tells the activity that a user pressed the favorite button.

In adapter:

public interface BookFavoriteListener {
    void onBookFavorited(Book book);
}

Implement the interface in your activity, then pass 'this' into the constructor of the adapter to set the listener.

Upvotes: 1

Related Questions