如何在 RecyclerView Adapter 中使用 Architecture Components ViewModel?
2022-09-01 07:01:32
我有多个 ViewHolder,它们在垂直 RecyclerView 中用作单独的视图。我正在练习新的架构组件视图模型。
在我的ViewModel中,我有几个可变LiveData列表,我想观察,但我如何调用
ViewModelProviders.of((AppCompatActivity)getActivity()).get(FilterViewModel.class)
和
mFilterViewModel.getCountries().observe(this, new Observer<ArrayList<TagModel>>() {
@Override
public void onChanged(@Nullable ArrayList<TagModel> tagModels) {
}
});
不泄漏活动或将活动保存在适配器内部?
我的视图模型
public class FilterViewModel extends ViewModel {
private final MutableLiveData<ArrayList<TagModel>> mCountries;
private final MutableLiveData<ArrayList<TagModel>> mSelectedCountryProvinceList;
private final MutableLiveData<ArrayList<TagModel>> mDistanceList;
public FilterViewModel(){
mCountries = new MutableLiveData<>();
mSelectedCountryProvinceList = new MutableLiveData<>();
mDistanceList = new MutableLiveData<>();
TagStore.getInstance().subscribe(new StoreObserver<TagSearchList>() {
@Override
public void update(TagSearchList object) {
mCountries.setValue(object.getCountries());
}
@Override
public void update(int id, TagSearchList object) {
if (id == 5){
TagStore.getInstance().unSubcribe(this);
update(object);
}
}
@Override
public void error(String error) {
}
}).get(5,"parent");
TagStore.getInstance().subscribe(new StoreObserver<TagSearchList>() {
@Override
public void update(TagSearchList object) {
mSelectedCountryProvinceList.setValue(object.toList());
}
@Override
public void update(int id, TagSearchList object) {
if (id == 6){
TagStore.getInstance().unSubcribe(this);
update(object);
}
}
@Override
public void error(String error) {
}
}).get(6,"parent");
TagStore.getInstance().subscribe(new StoreObserver<TagSearchList>() {
@Override
public void update(TagSearchList object) {
mDistanceList.setValue(object.toList());
}
@Override
public void update(int id, TagSearchList object) {
if (id == 51){
TagStore.getInstance().unSubcribe(this);
update(object);
}
}
@Override
public void error(String error) {
}
}).get(51,"parent");
}
public void selectCountry(final TagModel country){
TagStore.getInstance().subscribe(new StoreObserver<TagSearchList>() {
@Override
public void update(TagSearchList object) {
mSelectedCountryProvinceList.setValue(object.toList());
}
@Override
public void update(int id, TagSearchList object) {
if (id == country.getId()){
TagStore.getInstance().unSubcribe(this);
update(object);
}
}
@Override
public void error(String error) {
}
}).get(country.getId(),"parent");
}
public LiveData<ArrayList<TagModel>> getCountries(){
return mCountries;
}
public LiveData<ArrayList<TagModel>> getDistances(){
return mDistanceList;
}
public LiveData<ArrayList<TagModel>> getProvinces(){
return mSelectedCountryProvinceList;
}