LiveData observable data 儲存管理class。LiveData 根據 Activity、Fragment 或 Service 的生命週期處於活躍狀態才能做觀察做狀態更新。根據lifecycle-aware特性,當value改變時,View在前景便會直接發送,反之,在背景的話,value會被保留住,直到回到前景時才發送。此外,被destroy時,LiveData 自動停止observe行為,避免造成memory-leak。
動手作:
使用 MutableLiveData,提供setValue()和postValue()兩種更新value方式
class TodoViewModel: ViewModel() {
val todoLiveData = MutableLiveData<List<Todo>>(
mutableListOf(Todo.Title("This is a title"))
)
private var count = 0
fun addNewTodo() {
val todo = Todo.Item("note $count", false)
todoLiveData.value = todoLiveData.value!! + listOf(todo) //setValue
count ++
}
}
在使用資料的view observe 偵測資料是否更新
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
...........
val adapter = TodoAdapter()
recyclerView.adapter = adapter
...................
val todoViewModel = ViewModelProvider(this).get<TodoViewModel>()
todoViewModel.todoLiveData.observe(this, Observer { todos: List<Todo> ->
adapter.submitList(todos)
})
buttonAdd.setOnClickListener {
todoViewModel.addNewTodo()
}
}
}
reference:https://developer.android.google.cn/topic/libraries/architecture/livedata
reference:https://www.notion.so/LiveData-and-viewModel-9-2-bfb163f6dbfc4a71b2388538514de089
reference: https://ithelp.ithome.com.tw/articles/10193296