我有多个ViewHolder,它们作为竖直RecyclerView中的单独视图工作。我正在使用新的架构组件ViewModel进行练习。
在我的ViewModel中,我有几个MutableLiveData列表,我想观察它们,但是如何调用呢?
ViewModelProviders.of((AppCompatActivity)getActivity()).get(FilterViewModel.class)
和
(Note: This translates to "and" in English.)
mFilterViewModel.getCountries().observe(this, new Observer<ArrayList<TagModel>>() {
@Override
public void onChanged(@Nullable ArrayList<TagModel> tagModels) {
}
});
不泄漏活动或将活动保存在适配器内部?
我的ViewModelpublic 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;
}