You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
dependencies {
def lifecycle_version ="2.2.0"// ViewModel and LiveData
implementation "androidx.lifecycle:lifecycle-extensions:$lifecycle_version"// alternatively - just ViewModel
implementation "androidx.lifecycle:lifecycle-viewmodel:$lifecycle_version"// use -ktx for Kotlin// alternatively - just LiveData
implementation "androidx.lifecycle:lifecycle-livedata:$lifecycle_version"// alternatively - Lifecycles only (no ViewModel or LiveData). Some UI// AndroidX libraries use this lightweight import for Lifecycle
implementation "androidx.lifecycle:lifecycle-runtime:$lifecycle_version"
annotationProcessor "androidx.lifecycle:lifecycle-compiler:$lifecycle_version"// use kapt for Kotlin// alternately - if using Java8, use the following instead of lifecycle-compiler
implementation "androidx.lifecycle:lifecycle-common-java8:$lifecycle_version"// optional - ReactiveStreams support for LiveData
implementation "androidx.lifecycle:lifecycle-reactivestreams:$lifecycle_version"// use -ktx for Kotlin// optional - Test helpers for LiveData
testImplementation "androidx.arch.core:core-testing:$lifecycle_version"
}
class ViewModelActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
// Inflate view and obtain an instance of the binding class.
UserBinding binding = DataBindingUtil.setContentView(this, R.layout.user);
// Specify the current activity as the lifecycle owner.
binding.setLifecycleOwner(this);
}
}
前言
其实在学习过程中一直有接触到,但是始终是似懂非懂。对这个组件也没有一个初步的定位和理解。
我第一次想用LiveData的时候是在学习Binding特性的时候。但是对于数据的变化可以由Observable 代劳,LiveData并不是唯一的选择。这样就会产生一个疑惑,那么LiveData是为Binding而生的吗,那么既然没有LiveData也可以做Binding。那么LiveData的真正价值在哪里。我回答不了这个问题。只能暂时搁置,暂缓使用。
LiveData出道
我在实际使用过程中出现这样的场景。我想要在某个ViewModel中执行跳转到其他Activity的Intent操作,但是这个操作是不被Android设计者鼓励的
迫于无奈我只能写出这样别扭的诡异的代码
感觉就是革命不彻底的表现
LiveData终于横空出世
这是数据变化,和个特性和Observable有重合
这个特性才是关键,这里已经很明确说了,就是为Activity 和 Fragment量身定做的,目的就是建立起UI Control层(Activity,Fragment)和ViewModel的联系
LiveData家族(相关Package)
LiveData使用示例
在build.gradle中添加
implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0'
在MainViewModel.java中加入LiveData字段
泛型类代表传入显示Activity的类型
按钮触发的逻辑就是设置LiveData的值,把要跳转的Activity类型通知出去
MainActivity.java中订阅LiveData
这样清晰的多了,Activity里面还是做startActivity的事情,ViewModel管好业务和数据逻辑,大家各司其职。
LiveData的副产品 绑定通知
注意如果把 LiveData用做绑定需要加上 binding.setLifecycleOwner(this);
参考
LiveData 概览
将布局视图绑定到架构组件
The text was updated successfully, but these errors were encountered: