Reputation: 99
I have the following code:
class AddViewModel(application: Application) : AndroidViewModel(application) {
val readAllData: LiveData<List<DutyDay>>
private val repository: DutyDayRepository
init {
val dutyDayDao = DutyDayDatabase.getDatabase(
application
).dutyDayDao()
repository = DutyDayRepository(dutyDayDao)
readAllData = repository.readAllData
val date = readAllData.value?.get(1)?.date
}
As you can see, readAllData is a LiveData List of type dutyDay. I'm fetching the data from Room Database, and this DB is not empty, I use it in my recyclerView, all works fine.
But when I try to retrieve the date from my dutyDay object in index 1 of my readAllData List (last line in the code example), that variable contains null when debuging, whereas it is clearly not null in the database and as shown in the recyclerView? (not visible in the example)...
What am I doing wrong?
Thanks for your help :-)
Upvotes: 0
Views: 875
Reputation: 1427
Because LiveData is a life cycle aware component, it won't load any data until it has something observing it
So when its being loaded into your recyclerView, you would have observed/subscribed to it, so once the database has the value it would update the livedata and you would receive the value in the get() call as well
But what is happening here is your get() call is looking for the last value of your livedata object, which, due to not being observed, is null
Upvotes: 4