Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.3k views
in Technique[技术] by (71.8m points)

android - Room returning blank object

I'm posting my room query result using the below code

_data.postValue(databaseImpl.findRepoById(id).value)

But it seems the returned object is empty. I'm guessing we need to observe databaseImpl.findRepoById(id), not access it directly but since it's in a viewmodel I don't have a lifecycleOwner to assign to the room query livedata.

       databaseImpl.observe(this, Observer { //!!this is modelview and not activity
            _data.postValue()
        })

What is the right way to use Room query and update a mediator live data?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You could try use coroutines to query your data so you can have something like this for your DAO:

@Query("SELECT * FROM users") 
fun findRepoById(id): Flow<User>

In your DatabaseImpl class return have it as:

 fun findRepoById(id): Flow<User>  = userDao.findRepoById(id)

Then in your ViewModel you could do this:

viewModelScope.launch {
   databaseImpl.findRepoById(id).map { _data.postValue(it) }
}

Have a look at this article Room and Coroutines by Florina Muntenescu on how you could set up coroutines and use it with room.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...