为什么从接口调用 Dao 会破坏对 ViewModel 的观察?
Why calling Dao from an interface breaks the observation on ViewModel?
我尝试从接口调用 DAO
时遇到问题。
这里是我调用观察者方法的地方:
mCategories = ViewModelProviders.of(FragmentCategories.this).get(CategoriesViewModel.class);
//...
mCategories.getCategories(context).observe(this, listC -> {
ArrayList<Category> newList=new ArrayList<>(listC);
final DiffUtil.DiffResult result = DiffUtil.calculateDiff(
new CategoriesDif(list,newList), false);
list.clear();
list.addAll(newList);
result.dispatchUpdatesTo(myAdapter);
onItemsLoadComplete();
});
这是我将对象添加到数据库的时间:
private ColorPicked colorPicked = null;
//...
if (x) {
colorPicked = () - > {
Category c = new Category();
c.name = input.toString();
new AddCategoryOrLinkToDB().execute(c);
colorPicked = null;
dialog.dismiss();};
new ColorChooserDialog.Builder(MainActivity.this, R.string.color_palette)
.titleSub(R.string.colors)
.dynamicButtonColor(false)
.show(MainActivity.this);
} else {
Category c = new Category();
c.name = input.toString();
new AddCategoryOrLinkToDB().execute(c);
colorPicked = null;
dialog.dismiss();
}
//...
@Override
public void onColorChooserDismissed(@NonNull ColorChooserDialog dialog) {
if (colorPicked != null) {
colorPicked.chosen();
}
}
Why, if I call new AddCategoryOrLinkToDB().execute(c)
from
colorPicked
, the observer does not trigger and stops working?
我发现了问题。
在ViewModel中我使用了方法observeForever
,替换为observe
我解决了。
我尝试从接口调用 DAO
时遇到问题。
这里是我调用观察者方法的地方:
mCategories = ViewModelProviders.of(FragmentCategories.this).get(CategoriesViewModel.class);
//...
mCategories.getCategories(context).observe(this, listC -> {
ArrayList<Category> newList=new ArrayList<>(listC);
final DiffUtil.DiffResult result = DiffUtil.calculateDiff(
new CategoriesDif(list,newList), false);
list.clear();
list.addAll(newList);
result.dispatchUpdatesTo(myAdapter);
onItemsLoadComplete();
});
这是我将对象添加到数据库的时间:
private ColorPicked colorPicked = null;
//...
if (x) {
colorPicked = () - > {
Category c = new Category();
c.name = input.toString();
new AddCategoryOrLinkToDB().execute(c);
colorPicked = null;
dialog.dismiss();};
new ColorChooserDialog.Builder(MainActivity.this, R.string.color_palette)
.titleSub(R.string.colors)
.dynamicButtonColor(false)
.show(MainActivity.this);
} else {
Category c = new Category();
c.name = input.toString();
new AddCategoryOrLinkToDB().execute(c);
colorPicked = null;
dialog.dismiss();
}
//...
@Override
public void onColorChooserDismissed(@NonNull ColorChooserDialog dialog) {
if (colorPicked != null) {
colorPicked.chosen();
}
}
Why, if I call
new AddCategoryOrLinkToDB().execute(c)
fromcolorPicked
, the observer does not trigger and stops working?
我发现了问题。
在ViewModel中我使用了方法observeForever
,替换为observe
我解决了。