Convert LiveData to MutableLiveData

后端 未结 4 2048
天命终不由人
天命终不由人 2021-02-14 13:28

Apparently, Room is not able to handle MutableLiveData and we have to stick to LiveData as it returns the following error:

error: Not sure how to convert a Curso         


        
4条回答
  •  感情败类
    2021-02-14 13:42

    Call me crazy but AFAIK there is zero reason to use a MutableLiveData for the object that you received from the DAO.

    The idea is that you can expose an object via LiveData>

    @Dao
    public interface ProfileDao {
        @Query("SELECT * FROM PROFILE")
        LiveData> getProfiles();
    }
    

    Now you can observe them:

    profilesLiveData.observe(this, (profiles) -> {
        if(profiles == null) return;
    
        // you now have access to profiles, can even save them to the side and stuff
        this.profiles = profiles;
    });
    

    So if you want to make this live data "emit a new data and modify it", then you need to insert the profile into the database. The write will re-evaluate this query and it will be emitted once the new profile value is written to db.

    dao.insert(profile); // this will make LiveData emit again
    

    So there is no reason to use getValue/setValue, just write to your db.

提交回复
热议问题