我有多个 ViewHolders,它们在垂直 RecyclerView 中作为单独的视图工作。我正在使用新的架构组件 ViewModel 进行练习。
在我的 ViewModel 中,我有几个想要观察的 MutableLiveData 列表,但是我该如何调用
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;
}