"Poor Practices" are only poor Practices when you don't understand what are you doing surely and deeply.
1.为保证ViewModel拥有独立于Activity与Fragment的生命周期原则:
ViewModel不应包含任一Context实例及任何持有Context的Object如View等
2.仅在ViewModel进行数据处理,View层只对数据拥有读取的权限,为保证这一职责分离,需要封装数据对象,同时使用MutableLiveData<T>和LiveData<T>。具体操作如下:
在ViewModel中声明:
private val _clickValue = MutableLiveData<String>()
val clickValue: LiveData<String> get() = _clickValue
其中ViewModel中对私有对象_clickValue进行数据处理,而View层仅能通过订阅 clickValue对象驱动UI更新而不能对数据进行修改。
3.Fragment不可作为LifeCycleOwener传递给LiveData,否则可能造成对同一data有多个观察者。可以用getViewLifecycleOwner代替。
4.ViewModel层不应包含AndroidFramework类的引用,即没有android.* imports
(Android Framework:The android framework is the set of API's that allow developers to quickly and easily write apps for android phones. It consists of tools for designing UIs like buttons, text fields, image panes, and system tools like intents (for starting other apps/activities or opening files), phone controls, media players, ect.)
参考:
https://medium.com/wriketechclub/view-model-doesnt-have-to-depend-on-viewmodel-27f80808fe78
https://medium.com/android-news/mvvm-dos-and-don-ts-5950d6f347d4
https://developer.android.com/codelabs/kotlin-android-training-live-data?hl=zh-cn#5
https://stackoverflow.com/questions/2968016/android-framework-what-is-it/2969101
网友评论