[Android/Kotlin]MVVM 예제로 이해하기(1)

정민수·2024년 2월 16일

원래였으면 모든걸 액티비티에 몰아 넣어서 구현 했을 기능..
뷰모델 하나 추가하니 더 어려워졌따.!!

뷰모델을 사용하기 위한 gradle 추가

모듈 수준의 그래들에 의존성을 추가해준다.

implementation("androidx.activity:activity-ktx:1.8.2")
implementation("androidx.fragment:fragment-ktx:1.6.2")
implementation ("androidx.lifecycle:lifecycle-viewmodel-ktx:2.4.0")
implementation ("androidx.lifecycle:lifecycle-livedata-ktx:2.4.1")

data class

data class User(val name : String)

사용자 이름을 저장할 데이터 클래스를 하나 만들고~

ViewModel

뷰모델은 뷰와 모델의 중간다리 역할로 LiveData를 등록 시킨다.

class UserViewModel : ViewModel() {
    private val _user = MutableLiveData<User>()
    val user: LiveData<User> get() = _user

    fun setUserName(name: String) {
        _user.value = User(name)
    }
}

뷰모델을 설정 해주었다.

activity 레이아웃

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="16dp"
    tools:context=".MainActivity">

    <EditText
        android:id="@+id/editTextName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Enter your name" />

    <Button
        android:id="@+id/buttonSet"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Set Name" />

    <TextView
        android:id="@+id/textViewGreeting"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:textSize="18sp"
        android:textStyle="bold" />

</LinearLayout>

LiveData

Jeckpat 라이브러리에서 제공하는 클래스

수명 주기 인식: LiveData는 수명 주기를 인식하여 관찰자(Observer)에게 데이터 변경 사항을 알립니다. 이는 메모리 누수를 방지하고 사용자가 활성화된 상태에서만 데이터를 업데이트하는 데 도움이 됩니다.

UI 업데이트: LiveData는 UI 컨트롤러(예: 액티비티, 프래그먼트)와 함께 사용되어 UI의 상태를 업데이트하는 데 사용됩니다. 데이터가 변경될 때마다 관찰자에게 자동으로 알림을 보내므로 UI를 업데이트하는 코드를 별도로 작성할 필요가 없습니다.

데이터 홀더: LiveData는 데이터를 보유하고 관찰자에게 전달하는 데 사용됩니다. 이는 앱의 데이터를 관리하고, UI와 데이터 간의 결합도를 낮추는 데 도움이 됩니다.

반응형 프로그래밍: LiveData는 반응형 프로그래밍 패턴을 따르며, 데이터의 변경에 따라 자동으로 반응하여 UI를 업데이트합니다. 이는 앱의 사용자 경험을 향상시키는 데 도움이 됩니다.

MainActivity

LiveData를 관찰하는 observer

class MainActivity : AppCompatActivity() {
    private val viewModel : UserViewModel by viewModels()

    private val binding by lazy {ActivityMainBinding.inflate(layoutInflater)}

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)

        binding.buttonSet.setOnClickListener {
            val name = binding.editTextName.text.toString()
            viewModel.setUserName(name)
        }

        viewModel.user.observe(this, Observer { user ->
            binding.textViewGreeting.text = "Hello ${user.name}"
        })
    }
}
profile
응애...아무것도 모르는 개발자 흉내라도 내고 싶은 비전공자입니다.

0개의 댓글