【问题标题】:Why calling Dao from an interface breaks the observation on ViewModel?为什么从接口调用 Dao 会破坏对 ViewModel 的观察?
【发布时间】:2018-03-03 19:32:42
【问题描述】:

当我尝试从接口调用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();
    }
}

为什么,如果我打电话给new AddCategoryOrLinkToDB().execute(c) colorPicked,观察者不触发停止工作?

【问题讨论】:

    标签: android viewmodel dao android-room android-livedata


    【解决方案1】:

    我发现了问题。

    在 ViewModel 中我使用了 observeForever 方法,将其替换为 observe 我解决了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-03
      • 2018-05-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-18
      • 2015-01-03
      • 1970-01-01
      相关资源
      最近更新 更多