【问题标题】:How to get values from live data inside Repository class Room Database如何从存储库类房间数据库中的实时数据中获取值
【发布时间】:2018-11-17 21:46:13
【问题描述】:

我在我的应用程序中使用来自 android Jet-pack 的 Room Architecture 组件。我已经实现了 Repository 类,我在其中管理我的数据源,例如服务器和 Room 数据库中的数据。我正在使用实时数据来获取我的数据库中存在的所有对象的列表,并且我在我的活动类中附加了一个观察者。一切正常,除了在调用我的服务器之前的一件事我想检查房间中是否存在数据如果房间中存在数据我不想调用服务器以节省资源但是当我尝试从存储库类中的本地数据库获取数据它总是返回 null 我也尝试将观察者附加到它但没有用。

public LiveData<List<AllbrandsdataClass>> getAllBrands() {
    brandsDao.getallbrands().observeForever(new Observer<List<AllbrandsdataClass>>() {
        @Override
        public void onChanged(@Nullable final List<AllbrandsdataClass> allbrandsdataClasses) {
            final List<AllbrandsdataClass> listofbrandsobjectfromdb = allbrandsdataClasses;
            if (listofbrandsobjectfromdb == null) {
                Log.d(TAG, "Repository getallbrands number of brands in the DB is: 0");
            } else {
                // perform the logic to check and than fetch from server
            }
            return brandsDao.getallbrands();
        }
    }
}

这是我在接口类中的getAllBrands()方法,被注释为DAO

@Query("SELECT * FROM AllbrandsdataClass order by timeStamp  desc")
LiveData<List<AllbrandsdataClass>> getallbrands();

我想要的是在从服务器获取数据之前检查本地数据库中的数据的存储库类,但是在使用实时数据时我无法做到这一点,如上所示

【问题讨论】:

  • 你好 walter ,你找到正确的方法了吗?
  • 是的,我找到了。观看此youtu.be/2rO4r-JOQtA?t=340
  • 如果您还需要帮助,请告诉我。

标签: java android android-room android-livedata


【解决方案1】:

下面我使用 2 个“SumOfRowsFromDB”类型的实时数据流(收入、支出),您可以根据您的业务逻辑在存储库类中使用任何类型的实时数据“remainingIncome”,以获取 Long 类型的单个实时数据“remainingIncome” 首先,我将输入实时数据作为源添加到输出实时数据“remainingIncome”中,并在 lamda 中将输出实时数据的值设置为下面定义的方法,现在只要任何输入实时数据更改我的方法“combinedResult(收入,费用)”被调用,我可以根据我的业务逻辑相应地更改我的输出值。

 public LiveData<Long> getRemainingIncome() {
    MediatorLiveData<Long> remainingIncome = new MediatorLiveData<>();
    LiveData<SumOfRowsFromDB> income = mainDashBoardDao.getTansWiseSum(Constants.TRANS_TYPES.get(2));
    LiveData<SumOfRowsFromDB> expense = mainDashBoardDao.getTansWiseSum(Constants.TRANS_TYPES.get(1));
    remainingIncome.addSource(income, value -> {
        remainingIncome.setValue(combinedResult(income, expense));
    });
    remainingIncome.addSource(expense, value -> {
        remainingIncome.setValue(combinedResult(income, expense));
    });
    return remainingIncome;
}

private Long combinedResult(LiveData<SumOfRowsFromDB> income, LiveData<SumOfRowsFromDB> expense) {
    if (income.getValue() != null && expense.getValue() != null) {
        return (income.getValue().getSumOfRow() - expense.getValue().getSumOfRow());
    } else {
        return 0L;
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-22
    • 1970-01-01
    • 2020-05-20
    • 2021-08-06
    • 2019-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多