---
# System prepended metadata

title: Live Data & LiveData Observers
tags: [Live Data, Android, kotlin]

---

# Live Data & LiveData Observers

## [沿用viewModel的程式碼](https://hackmd.io/2jzgiOv1Sx27ZxByoReY6g?view)

## Live Data是一種observable data holder class，並且在資料變更時通知observers

1. ### 修改MainViewModel.kt
    #### 將原本的count宣告為 MutableLiveData類型
    #### 程式碼第2~4行是封裝寫法，分為內部與外部變數，_count是屬於內部運算使用，count是屬於要更新於UI的data
    
    
```kotlin=0
class MainViewModel : ViewModel() {
    // TODO: Implement the ViewModel
    private val _count = MutableLiveData<Int>()
    val count : LiveData<Int>
        get() = _count
//    var count = 0
    init {
        _count.value = 0
    }
    //執行+1
    fun onadd(){
        _count.value = (count.value)?.plus(1)
//        count++
    }
    //執行-1
    fun ondes(){
        _count.value = (count.value)?.minus(1)
    }

    override fun onCleared() {
        super.onCleared()
    }
}
```

2. ### 修改MainFragment.kt
    #### 新增程式碼第29~30行，設定一個observer觀察count數值變化，一旦數值變化就執行第30行更新UI畫面
    #### 因為已經設定observer來更新UI了，所以把updateData這個函數功能拿掉
    #### 額外增加一個按鈕與函數，是執行-1的計算
    
```kotlin=0
class MainFragment : Fragment() {

    companion object {
        fun newInstance() = MainFragment()
    }
    private lateinit var binding : MainFragmentBinding
    private lateinit var viewModel: MainViewModel

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                              savedInstanceState: Bundle?): View {
        binding =DataBindingUtil.inflate(
                inflater,
                R.layout.main_fragment,
                container,
                false
        )
        return binding.root
//        return inflater.inflate(R.layout.main_fragment, container, false)

    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        Log.i("onViewCreated", "view created")

        viewModel = ViewModelProvider(this).get(MainViewModel::class.java)
        // TODO: Use the ViewModel
        //註冊兩顆按鈕的click監聽器
        binding.plus.setOnClickListener { madd() }
        binding.minus.setOnClickListener { mdes() }
        viewModel.count.observe(viewLifecycleOwner, Observer { newCount ->
            binding.keepsave.text = newCount.toString()
        })
//        updateData()
    }
    //onActivityCreated 不會使用到，可以刪除了
    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        Log.i("onActivityCreated", "onActivityCreated")

    }
    //執行加法運算
    fun madd(){
        viewModel.onadd()
//        updateData()
    }
    //執行減法運算
    fun mdes(){
        viewModel.ondes()
    }

//    fun updateData(){
//        binding.keepsave.text = viewModel.count.value.toString()
//        binding.keepsave.text = viewModel.count.toString()
//    }

}
```
### 以上
[參考資料]  [code lab](https://developer.android.com/codelabs/kotlin-android-training-live-data#3)

###### tags: `kotlin` `Android` `Live Data` 