[英]How to observe database delete events with Architecture Components
I have a DAO as follows. 我有一个DAO如下。
@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? 但是如何知道帖子何时被删除?
LiveData<List<Post>> getPosts();
returns a LiveData
that is updated by any insert
, update
, or delete
done to the Post table. 返回通过对Post表执行的任何insert
, update
或delete
更新的LiveData
。
So if you are observing the list initially, then you are already observing for inserts/updates/deletes. 因此,如果您最初观察列表,那么您已经在观察插入/更新/删除。
You observe for all the items ( LiveData<List<Post>>
) and get notified with the new data as soon as something changes. 您可以观察所有项目( LiveData<List<Post>>
),并在出现更改时立即收到新数据通知。
You may want to use the new DiffUtil which can show you the affected changes. 您可能希望使用新的DiffUtil ,它可以显示受影响的更改。
Another way is to set/update the value of your LiveData after deleting. 另一种方法是在删除后设置/更新LiveData的值。 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? 我写了一个答案为什么删除和插入不在Android Room使用LiveData :更新插入的LiveData回调?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.