LiveData和ViewModel的關(guān)系
-
在ViewModel中的數(shù)據(jù)發(fā)生變化是通知頁面
image.png
當ViewModel數(shù)據(jù)發(fā)生變化通過LiveData通知View數(shù)據(jù)變化進行更新
LiveData應(yīng)用:
- 非UI線程使用postValue
- UI線程使用setValue
class MyViewModel :ViewModel() {
private lateinit var liveData:MutableLiveData<Int>
fun getCurrentSecond():MutableLiveData<Int>{
if(!this::liveData.isInitialized){
liveData = MutableLiveData()
liveData.value = 0
}
return liveData
}
}
class Test2Activity : AppCompatActivity() {
private var viewModel: MyViewModel? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_test2)
viewModel =
ViewModelProvider(this, ViewModelProvider.AndroidViewModelFactory(application)).get(
MyViewModel::class.java
)
findViewById<TextView>(R.id.textView).text = viewModel?.getCurrentSecond()?.value.toString()
viewModel?.getCurrentSecond()?.observe(this) {
findViewById<TextView>(R.id.textView).text = it.toString()
}
startTime()
}
private fun startTime() {
Timer().schedule(
object : TimerTask() {
override fun run() {
viewModel?.getCurrentSecond()
?.postValue((viewModel?.getCurrentSecond()?.value?.plus(1)))
}
},
1000,
1000
)
}
}
LiveData的優(yōu)勢:
- 確保頁面符合數(shù)據(jù)狀態(tài)
- 不會發(fā)生內(nèi)存泄漏
- 不會因Activity停止而導(dǎo)致崩潰
- 不在需要手動處理生命周期
- 數(shù)據(jù)始終保持最新狀態(tài)
- 適當?shù)呐渲酶?/li>
- 共享資源