【发布时间】:2019-11-06 12:41:19
【问题描述】:
我有一个常规的 Room->DAO->Livedata->Repositiry->ViewModel->RecyclerView 应用程序。 UI 的不同按钮必须将不同的数据列表传递给 RecyclerView。
按我想要的按钮点击:
- 在 DAO 中创建新的 @Query 并获得新的 LiveData 对象作为回报。
- 将这些新数据放入RecyclerViewAdapter 并调用notifyDataSetChanged() 来制作新的List 视觉效果。
道@查询:
@Query("SELECT * FROM entry_table WHERE path LIKE :path ORDER BY priority DESC")
LiveData<List<Entry>> getNotesOfFolder(String path); //Returns LiveData with List of Entries
recyclerView 是通过 Observer 的 onChanged 更新的,如下所示:
public class RecyclerViewActivity extends AppCompatActivity {…
Observer<List<Entry>> entryObserver = new Observer<List<Entry>>() {
@Override
public void onChanged(List<Entry> entries) {
recyclerAdapter.setEntries(entries);
}
};
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.EntryHolder> {…
public void setEntries(List<Entry> entries) {
this.entries = entries; //setting LiveData content to adapter's List (i.e. entries)
notifyDataSetChanged();
问题是当 LiveData 从 DAO 接收到新值时,我的 Observer 没有调用 onChange 方法。我相信这是因为这个 LiveData 的内容没有被改变,而是被另一个 LiveData 替换。
我尝试再次将 Observer 重新订阅到 LiveData 并且它有点工作,但是当我尝试调用一些常规的 Room 查询(如 @Delete)时,我收到了多个(最多 10 个!)onChange 调用,其中一些行为怪异并将错误的列表传递给 RVadapter。
所以有两个问题:
- 我怎样才能调用我的观察者的 onChanged()?
- 是否有其他时尚的方式将新的 LiveData 对象动态传递给 RecyclerView?
【问题讨论】:
-
我希望您建议在您的页面中设置
refresh功能。例如,将SwipeRefreshLayout添加到您的布局中。我认为这可能有助于获取更新的数据。
标签: android android-recyclerview android-room android-livedata