ViewModel与LiveData如何监听数据变化更新试图
ViewModel用来可感知生命周期的方式存储和管理UI相关数据,当系统配置发生变更的时候,如屏幕旋转,数据不会丢失。
主要步骤:
1.ViewModel关联了数据LiveData
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public class HomeViewModel extends ViewModel { private MutableLiveData<String> mText; public HomeViewModel() { mText = new MutableLiveData<>(); mText.setValue("This is home fragment"); } public LiveData<String> getText() { return mText; } }
((MutableLiveData<String>)homeViewModel.getText()).postValue("");写在onCreateView中肯定是不合适的,不要介意这个。😋
2.在activity或者fragment中,通过ViewModal的LiveData,在在activity或者fragment上注册监听Observer,Observer的回调方法中执行视图更新。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public class HomeFragment extends BaseFragment { String TAG="TAGHomeFragment"; private HomeViewModel homeViewModel; public HomeFragment(){ super.TAG = this.TAG; Log.i(TAG, "HomeFragment: "); } public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { Log.i(TAG, "onCreateView: "); homeViewModel = new ViewModelProvider(this).get(HomeViewModel.class); View root = inflater.inflate(R.layout.fragment_home, container, false); final TextView textView = root.findViewById(R.id.text_home); homeViewModel.getText().observe(getViewLifecycleOwner(), new Observer<String>() { @Override public void onChanged(@Nullable String s) { textView.setText(s); } }); ((MutableLiveData<String>)homeViewModel.getText()).postValue(""); return root; } }
3.ViewModal的LiveData通过postValue,最终会执行Observer的回调方法
((MutableLiveData<String>)homeViewModel.getText()).postValue("");
接下来我们来耕种一下代码,从((MutableLiveData<String>)homeViewModel.getText()).postValue("");开始。
1)执行postValue
2.在postValue中,把数据value放在了mPendingData上;并通过线程mPostValueRunnable执行更新
3)mPostValueRunnable把mPendingData赋值给newValue,然后执行setValue
4)setValue把数据放在了mData上,并执行dispatchingValue
5)再执行considerNotify
6)considerNotify中会执行mObserver的onChange回调方法。onChange的实现在activity或者fragment中,这样就可以更新试图
7)最后在看mObserver怎么来的。
是通过在activity或者fragment注册监听的时候,把mObserver初始化的