Skip to content Skip to sidebar Skip to footer

Room Database Doesn't Run My Implemented Transaction On Background Thread

This question is a solution I've tried for my other question, so if you have a solution to the first one that avoids this question problems, I'm all ears. So I have this method in

Solution 1:

it appears that I don't to include my code inside any executer when using LiveData as return value from Dao queries. Room really execute queries on background only if it results from its abstract queries not the one I wrote.

so my code looks like this at the end :

my Dao

@Dao
public abstract class UserDao {
    @Query("Select * from page")
    public abstract LiveData<List<PageEntity>> getAllPages ();
    @Transaction@Query("Select * from user limit 1")
    public abstract LiveData<UserPageRelation> getAllUserPages ();   
}

my ViewModel

publicclassMyViewModelextendsViewModel {

    privateMediatorLiveData<PagesCombinedData> pagesCombinedData;
    publicLiveData<PagesCombinedData> getPageCombinedData(){
           if (pagesCombinedData==null){
               pagesCombinedData = new MediatorLiveData<>();
           }
           LiveData<List<PageEntity>> value1 = scheduleDB.userDao().getAllPages();
           LiveData<UserPageRelation> value2 = scheduleDB.userDao().getAllUserPages();
           pagesCombinedData.addSource(value1, value -> pagesCombinedData.setValue(combineData(value1,value2)));
           pagesCombinedData.addSource(value2, value -> pagesCombinedData.setValue(combineData(value1,value2)));
           return pagesCombinedData;
    }
    privatePagesCombinedData combineData(LiveData<List<PageEntity>> pages,LiveData<UserPageRelation> userPages ){
        return new PagesCombinedData(pages.getValue()==null?new ArrayList<>():pages.getValue()
                ,userPages.getValue()==null ?new ArrayList<>():userPages.getValue().getUserPages());
    }
}

and that work like charm returning the MediatorLiveData that I could observe from both of the data lists I wanted.

Post a Comment for "Room Database Doesn't Run My Implemented Transaction On Background Thread"