2

I have a DAO as follows.

@Dao
public interface PostDAO {
    @Query("SELECT * FROM posts order by time DESC")
    LiveData<List<Post>> getPosts();

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    @NonNull
    void insert(Post... posts);

    @Delete
    void delete(Post post);

    @Query("SELECT * FROM posts WHERE id = :id")
    Post getPost(String id);

    @Query("SELECT * FROM posts WHERE id = :id")
    LiveData<Post> getPostLiveData(String id);
}

I understand that I can listen for new added data with something like the following.

postDAO().getPosts().observe(builder.getLifecycleOwner(), data::postValue)

But how can I know when a post has been deleted?

Relm
  • 7,923
  • 18
  • 66
  • 113

2 Answers2

2

LiveData<List<Post>> getPosts(); returns a LiveData that is updated by any insert, update, or delete done to the Post table.

So if you are observing the list initially, then you are already observing for inserts/updates/deletes.

EpicPandaForce
  • 79,669
  • 27
  • 256
  • 428
  • But how can you tell specifically which event it is for? Checkout my question here: https://stackoverflow.com/q/57948812/1219213 – TheRealChx101 Sep 15 '19 at 23:32
1

You observe for all the items (LiveData<List<Post>>) and get notified with the new data as soon as something changes.

You may want to use the new DiffUtil which can show you the affected changes.

Another way is to set/update the value of your LiveData after deleting. Returning Long means that it returns the count of the deleted rows.

@Delete void delete(Post post) : Long

LiveData data = new MutableLiveData<Post>()
if (yourDao.delete(yourItem) > 0) data.setValue( yourItem ) 

I wrote an answer why Delete and Insert is not using LiveData at Android Room : LiveData callback of update insert?

Emanuel
  • 8,027
  • 2
  • 37
  • 56
  • your answer before the edit about using Single can you elaborate on that in the comment. – Raghunandan Oct 11 '17 at 15:10
  • Dont know what you mean :-) You can either check for changes using some kind of DiffUtil (or the android provided helper for that) or you use the attempt ive posted using another MutableLiveData<> which get notified as soon as data has been changed. Depends on the use case. If you have a "big" list the approach using a new LiveData Object is the best way to go. – Emanuel Oct 11 '17 at 15:12
  • Shouldn't it be wise to encourage using the "DiffUtil routine" over setValue()? I've been using data.setValue();, with post though, something's just not right with it. – Relm Oct 11 '17 at 15:13
  • i understand. i thought i saw something related to Single before the edit. Anyway i got your point. – Raghunandan Oct 11 '17 at 15:13