Search code examples
androidandroid-roomandroid-livedataandroid-jetpackandroid-viewmodel

Binding on a not (yet) initialized livedata element


maybe the headline does not fit the question really well so I'll explain it.

In my app I send a request to a server to get gerneral user information. If I receive on I want to save it into the local room db. Now we come to the problem. I want to bind this one user to the view directly out of the db. But I can not bind a element, which maybe does not exists, because the request is in progress.

(My bad solution): Creating another livedate element which holds a boolean. I create a observer in the Activity and add the observer after the boolean observes a "true". With this solution I can not use "Data Binding" in the xml layout.

Does anyone have an idea? (If you need further information just ask - I know it is a really abstract question without any code)


Solution

  • As Sanlok Lee mentioned:

    If you reassign user then it becomes a completely different instance and the observer will not listen to the new LiveData. Instead you can do val user: MediatorLiveData<User> and later you can call user.addSource(dao.getUserById(1), ...)

    OR: Just load the user (also if you know that there is no one in the DB) from the DB. You can do that in you UserRepository for example.

    val user: LiveData<User> = userDao.getUser()
    

    The Livedata will get notified when there is a valid user inserted.