简体   繁体   中英

How to get values from live data inside Repository class Room Database

I am using Room Architecture component from android Jet-pack in my App. I have implemented the Repository class where I manage my data sources like server and data from Room database. I am using live Data to get a list of all the objects present in my database and I have attached an Observer in my activity class. All works perfectly except one thing before making a call to my server I want to check if data is present in Room or not if data is present in Room I do not want to make a call to the server to save resources But when I try to get the data from local database in repository class it always returns null I have also tried attaching an observer to it but no use.

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();
        }
    }
}

here is my getAllBrands() method in the interface class which is annotated as DAO

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

what I want is to perform a check in repository class for data from the local database before fetching the data from the server but I am unable to do it when using live data as shown above

Below I am using 2 live data streams(income, expense) of type "SumOfRowsFromDB" yours can be any depending upon your business logic, in the repository class to get a single live data "remainingIncome" of type Long first, I added both my input live data as source to my output live data "remainingIncome" and in the lamda I set the value of my output live data as a method that is defined below, now whenever any of the input live data changes my method "combinedResult(income, expense)" gets called and I can change the value of my output accordingly as per my business logic.

 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;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM