gpt4 book ai didi

android - 在 AndroidViewModel 中初始化 LiveData

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:37:56 24 4
gpt4 key购买 nike

我正在寻找一种方法来初始化 ViewModel 中的 LiveData 对象。当前仅在从 Activity 调用 setQuery 方法时才初始化项目。

public class MyListViewModel extends AndroidViewModel {

private final LiveData <List<Item>> items;
private final MutableLiveData<String> query = new MutableLiveData<>();


private MyDatabase db;

public MyListViewModel(Application application) {
super(application);
db = MyDatabase.getInstance(application);
items = Transformations.switchMap(query, (search)->{
if (search == null || search.trim().length() == 0) {
return db.itemDao().getAllItems();
} else {
return db.itemDao().findItemsBySearchTerm(search);
}
});

}

public LiveData<List<Item>> getItems() {
return items;
}

public void setQuery(String queryText) {
query.setValue(queryText);
}

最佳答案

您必须调用 setQuery(String queryText) 至少一次根据转换文档

The transformations aren't calculated unless an observer is observing the returned LiveData object. Because the transformations are calculated lazily, lifecycle-related behavior is implicitly passed down without requiring additional explicit calls or dependencies.

所以如果你不调用setQuery(String queryText)从 Activity 中它不会更新 MutableLiveData<String> query并且不会触发转换。

如果你想避免来自Activity的初始调用,你可以像这样在Transformation初始化下面调用它,

public MyListViewModel(Application application) {
super(application);
db = MyDatabase.getInstance(application);
items = Transformations.switchMap(query, (search)->{
if (search == null || search.trim().length() == 0) {
return db.itemDao().getAllItems();
} else {
return db.itemDao().findItemsBySearchTerm(search);
}
});
setQuery("")
}

它将触发空搜索部分并返回所有项目

您还需要观察您案例中返回的数据items .如果没有观察者在观察数据,那么事务将不会触发。

正如我从 Documentation 中提到的那样很少有博客对我有用

关于android - 在 AndroidViewModel 中初始化 LiveData,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48044211/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com