Reputation: 4607
In room
, I have a dao to something like this:
@Dao
interface FacultyDao {
@Query("select * from faculty")
fun getAll(): LiveData<List<Faculty>>
...
}
And inside the repository, I'm simply calling this method and logging it:
class FacultyRepository(application: Application) {
private val facultyDao: FacultyDao
init {
val db: AppDB = AppDB.getInstance(application)
facultyDao = db.facultyDao()
}
fun getAllFaculty(): LiveData<List<Faculty>> {
val v = facultyDao.getAll()
Log.d("muaxx", v.value.toString())
return v
}
...
}
But the thing is it's returning me null
, but when I ran that query in inspector it worked. Am I missing something?
Upvotes: 0
Views: 555
Reputation: 4607
Here is what I have done:
facultyRepository
inside AndroidViewModel
, like this: private val facultyRepository = FacultyRepository(application)
faculties
) to store the result in some mutable livedata, like this: val faculties: MutableLiveData<List<Faculty>> = MutableLiveData(ArrayList())
init
I'm observing the getAllFaculty
using observeForever
And yes, I need to call this init
method once, from the fragment.
Relevant code:
class FacultyListViewModel(application: Application) : AndroidViewModel(application) {
private val facultyRepository = FacultyRepository(application)
val faculties: MutableLiveData<List<Faculty>> = MutableLiveData(ArrayList())
fun init() {
facultyRepository.getAllFaculty().observeForever {
faculties.postValue(it)
}
}
}
If you have got some better approach, feel free to suggest here.
Upvotes: 0
Reputation: 31
Live data gives us real-time data. Therefore, for the first time, you still don't have some in yourself. And it is waiting for the response of the database. If you want to see some of the live data, you must observe it so that after receiving the information, the observer will be called and the information will be logged.
Upvotes: 1
Reputation: 93601
LiveData doesn’t immediately have an initial value. Room queries the database and gets the result on a background thread. Then on the next loop of the main thread, the LiveData’s value
will be set to this retrieved value. You are logging value
too early. The initial value is going to appear some time in the future, after this function has already returned.
Normally you should only be getting a LiveData value through observing it.
Directly checking the value
should usually only be done when you are managing a MutableLiveData and are using the previous value to help determine the next value that you are going to post.
Upvotes: 1