Android Room:插入LineItem时如何触发Allocation查询的观察者?
问题解答
执行insertAll(LineItem... lineItems)无法触发getAllocations()的观察者,原因如下:
Room中LiveData的自动更新机制基于查询语句涉及的表:只有当查询关联的表发生增、删、改操作时,Room才会通知对应的LiveData观察者刷新数据。getAllocations()的查询目标是allocation表,而insertAll(LineItem...)操作的是lineitem表,这两个表在当前查询逻辑中未被Room关联监听,所以插入LineItem不会触发Allocation查询的LiveData更新。
解决办法
如果需要在LineItem数据变化时同步更新Allocation的LiveData,可以采用以下两种方案:
方案1:修改查询语句关联两张表
调整getAllocations()的SQL语句,通过关联查询让Room同时监听allocation和lineitem表:
@Query("SELECT a.* FROM allocation a LEFT JOIN lineitem li ON a.id = li.allocation_id") LiveData<List<Allocation>> getAllocations();
此时Room会监控这两张表的任何数据变化,当插入LineItem时,会自动触发该LiveData的观察者更新。
方案2:使用Room的@Relation关联实体
定义包含关联关系的实体类,让Room自动处理关联表的变化监听:
- 创建包含关联关系的实体类:
public class AllocationWithLineItems { @Embedded public Allocation allocation; @Relation( parentColumn = "id", entityColumn = "allocation_id" ) public List<LineItem> lineItems; }
- 在DAO中添加对应的查询方法:
@Query("SELECT * FROM allocation") LiveData<List<AllocationWithLineItems>> getAllocationsWithLineItems();
使用这个方法替代原有的getAllocations(),当lineitem表数据变化时,Room会自动通知该LiveData的观察者刷新,同时你还能直接获取到每个Allocation对应的LineItem列表。
内容的提问来源于stack exchange,提问作者Jason John
相关产品推荐
相关产品推荐

