Reputation: 41
I am unable to get a LiveData ArrayList from a Room database but I am able to retrieve a standard ArrayList and cannot figure out why.
I have run this code in debug mode and the ArrayList returns a size of 4, which it should. The LiveData ArrayList, when get value is used returns null. I have run the LiveData query both within an executor and outside of the executor and it returns null.
Declarations
public LiveData<List<CourseEntity>> courseEntities;
private List<CourseEntity> courseData = new ArrayList<>();
Code outside of executor
public void loadData(final int termId) {
courseEntities = courseRepository.getCourseByTermId(termId);
courseData = courseEntities.getValue();
}
Code inside executor
public void loadData(final int termId) {
executor.execute(new Runnable() {
@Override
public void run() {
courseEntities = courseRepository.getCourseByTermId(termId);
courseData = courseEntities.getValue();
}
});
}
Code using just an ArrayList
public void loadData(final int termId) {
executor.execute(new Runnable() {
@Override
public void run() {
courseData = courseRepository.getCourseByTerm(termId);
}
});
}
Queries from Dao
@Query("SELECT * FROM course " +
"WHERE term_id = :termIdSelected ORDER BY course_start" )
LiveData<List<CourseEntity>> getCourseByTermId(int termIdSelected);
@Query("SELECT * FROM course WHERE term_id = :termIdSelected ORDER BY course_start")
List<CourseEntity> getCourseByTerm(int termIdSelected);
This produces a null value for the LiveData instead of a value of 4 like the plain ArrayList produces. The only difference being the LiveData wrapper for the result. Any wisdom someone can share would be most appreciated.
Upvotes: 1
Views: 987
Reputation: 1007286
When you have a Room @Dao
return a LiveData
(or an RxJava type like Observable
or Single
), the generated implementation will do the actual work on a background thread. So, when getCourseByTermId()
returns, the work will not yet have begun, so the LiveData
will not have results yet.
Reactive types, like LiveData
, are meant to be observed. So, your activity/fragment/whatever would observe()
the LiveData
and react to the result when it is delivered.
Upvotes: 1