我正在尝试更改房间数据库时更新RecyclerView。但是,当发生对数据库的更改时,不会调用MainActivity中定义的观察者的onChanged方法。如果我让DAO返回LiveData而不是List<>并在我的ViewModel中使用LiveData,它按预期工作。但是我需要MutableLiveData,因为我想在运行时将我的查询更改为数据库。
我的设置:
MainActivity.java
BorrowedListViewModel viewModel = ViewModelProviders.of(this).get(BorrowedListViewModel.class);
viewModel.getItemAndPersonList().observe(MainActivity.this, new Observer<List<BorrowModel>>() {
@Override
public void onChanged(@Nullable List<BorrowModel> itemAndPeople) {
recyclerViewAdapter.addItems(itemAndPeople);
}
});
BorrowedListViewModel.java
public class BorrowedListViewModel extends AndroidViewModel {
private final MutableLiveData<List<BorrowModel>> itemAndPersonList;
private AppDatabase appDatabase;
public BorrowedListViewModel(Application application) {
super(application);
appDatabase = AppDatabase.getDatabase(this.getApplication());
itemAndPersonList = new MutableLiveData<>();
itemAndPersonList.setValue(appDatabase.itemAndPersonModel().getAllBorrowedItems());
}
public MutableLiveData<List<BorrowModel>> getItemAndPersonList() {
return itemAndPersonList;
}
//These two methods should trigger the onChanged method
public void deleteItem(BorrowModel bm) {
appDatabase.itemAndPersonModel().deleteBorrow(bm);
}
public void addItem(BorrowModel bm){
appDatabase.itemAndPersonModel().addBorrow(bm);
}
}
BorrowModelDao.java
public interface BorrowModelDao {
@Query("select * from BorrowModel")
//Using LiveData<List<BorrowModel>> here solves the problem
List<BorrowModel> getAllBorrowedItems();
@Query("select * from BorrowModel where id = :id")
BorrowModel getItembyId(String id);
@Insert(onConflict = REPLACE)
void addBorrow(BorrowModel borrowModel);
@Delete
void deleteBorrow(BorrowModel borrowModel);
}
AppDatabase.java
public abstract class AppDatabase extends RoomDatabase {
private static AppDatabase INSTANCE;
public static AppDatabase getDatabase(Context context) {
if (INSTANCE == null) {
INSTANCE =
Room.databaseBuilder(context.getApplicationContext(), AppDatabase.class, "borrow_db")
.allowMainThreadQueries()
.build();
}
return INSTANCE;
}
public static void destroyInstance() {
INSTANCE = null;
}
public abstract BorrowModelDao itemAndPersonModel();
}