LiveData란 안드로이드에서 데이터를 관리하는 방법중에 하나이다.
앱의 상태(라이프사이클)에 따라 데이터를 관찰하고,앱의 상태가 바뀔때마다 그에 맞게 데이터를 업데이트하게끔 만들수 있다.
즉 데이터가 변경되면 observer을 통해 Ui에 즉각적으로 업데이트 할 수 있다.
라이프사이클: 앱이 실행되고 사용되다가 종료되는 과정. 여러단계가 있다.
class MainActivity : AppCompatActivity() {
// 라이브데이터의 초기값을 0으로 세팅한다.
private var testMutableLiveData = MutableLiveData(0)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// 버튼을 누를때마다 라이브데이터의 값을 1씩 더한다.
findViewById<Button>(R.id.btnArea).setOnClickListener {
testMutableLiveData.value = testMutableLiveData.value!!.plus(1)
}
// 라이브데이터를 통해 데이터의 변화를 관찰하고, 변화될때마다 로그와 UI에 값을 반영하도록한다
testMutableLiveData.observe(this, Observer {
Log.d("testMutableLiveData", testMutableLiveData.value.toString())
findViewById<TextView>(R.id.textArea).text = testMutableLiveData.value.toString()
})
}
}
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/textArea"
android:textSize="60dp"
android:text="0"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<Button
android:id="@+id/btnArea"
android:text="btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
이렇게 하면 클릭을 할때마다 데이터가 증가하는게 로그에 찍힘과 동시에 ui에도 반영이 되는걸 볼수 있다.
하지만 viewModel을 사용하지 않기 때문에 화면을 회전할 경우 엑티비티가 재생성되면서 데이터가 초기화된다.