【问题标题】:Update UI With Live Data & Not MutableLiveData - Room Database使用实时数据而不是 MutableLiveData 更新 UI - 房间数据库
【发布时间】:2021-04-29 05:48:35
【问题描述】:

所以我有这个 Dao,我声明了一个 LiveData 方法。

@Dao
public interface EarthquakeDao {

    @Insert
    public void insert(Properties properties);

    @Query("select * from properties")
    public LiveData<List<Properties>> getAllProperties();

}

我的 ViewModel 中有一个 sortByTitle 方法。

    public void sortByTitle(){
            Collections.sort(propertiesList.getValue(), new Comparator<Properties>() {
                @Override
                public int compare(Properties o1, Properties o2) {
                    return o1.title.compareTo(o2.title);

                }
            });
            propertiesList.postValue(featuresList.getValue());
    }

由于propertiesListLiveData 而不是MutableLiveData,所以我无法使用postValue 方法更新用户界面。

为了更新 UI,我需要使用MutableLiveData,另一方面...我的数据库给了我一个LiveData 对象。所以我无法做到这一点。

另外,我不能将 Dao 的方法设为 MutableLiveData,我知道。

那我该如何实现呢?

【问题讨论】:

    标签: android mvvm android-room android-mvvm


    【解决方案1】:

    您可以简单地 map 来自 RoomLiveData。例如:

    public LiveData<List<Properties>> properties = Transformations.map(propertiesList, list -> {
      return sort(list);
    })
    

    更多信息请参见Transformations.map

    【讨论】:

    • 有没有办法在 Java 中做到这一点?
    • 是的,应该可以使用上面的方法,你应该用你的排序方法替换sort()
    猜你喜欢
    • 2019-01-17
    • 1970-01-01
    • 2022-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多