2025. 4. 12. 05:06ㆍKotlin
안녕하세요~
2025.04.08 - [Kotlin] - 1. 실전 MVVM 합니다.
이전 글에 이어서 실전 편입니다.
위 링크의 3~6 단계를 다루고 있습니다. (LiveData란? ~ LiveData객체에 관찰자 연결하기
MVVM에서 View Model에 들어가는 Live Data을 다뤄볼 것입니다.
1. 뒤섞인 글자인 새로운 단어를 Live Data에 추가합니다.
[부연설명] Kotlin 기본문법
MutableLiveData는 LiveData의 저장된 변수 값을 변경할 수 있는 변수의 종류입니다. 함수형 패러다임을 지향하는 코틀린에서는 기존 Java와는 다르게 저장된 값을 변경할 수 있다면 Mutable이라는 접두사가 들어갑니다.
그냥 LiveData라고 하면, 저장된 변수값을 변경할 수 없는 것이라고 구분하시면 됩니다.
class GameViewModel : ViewModel() {
...
// 뒤섞인 단어를 관잘하기 위해서, MutableLiveData로 변수를 선언합니다.
private val _currentScrambledWord = MutableLiveData<String>()
private fun getNextWord() {
...
} else {
// MutableLiveData 내의 데이터에 액세스를 위해 .value를 이용합니다.
_currentScrambledWord.value = String(tempWord)
...
}
}
...
}
2. 데이터를 관찰하기 위해 MutableLiveData 선언합니다. 그 후 각 Mutable LiveData에 viewLifeCycleOwner를 연결합니다.
Unscramble 게임앱에서 데이터를 다루는 곳은 3군데가 있습니다.
1. 새로운 단어
2. 점수
3. 맞춘 워드의 수
이 3가지에 대해서 데이터를 관잘하는 코드를 GameFragment.kt파일에 넣습니다.
class GameFragment : Fragment() {
...
// 점수를 저장하는 LiveData를 선언합니다.
private val _score = MutableLiveData(0)
val score: LiveData<Int>
get() = _score
// 총 문제 갯수를 저장하는 LiveData를 선언합니다.
private val _currentWordCount = MutableLiveData(0)
val currentWordCount : LiveData<Int>
get() = _currentWordCount
...
}
2-1. 문제 제출 버튼에 다음 과 같은 코드를 작성합니다.
class GameFragment: Fragment(){
...
//다음과 같이 유저가 제출한 단어가 맞는치 확인하는 함수를 제작합니다.
private fun onSubmitWord() {
val playerWord = binding.textInputEditText.text.toString()
if (viewModel.isUserWordCorrect(playerWord)) {
setErrorTextField(false)
if (!viewModel.nextWord()) {
showFinalScoreDialog()
}
} else {
setErrorTextField(true)
}
}
...
}
2-2. 각 Mutable LiveData에 viewLifeCycleOwner를 연결합니다.
class GameFragment : Fragment() {
...
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
...
// 기본값 설정
binding.score.text = getString(R.string.score,0)
binding.wordCount.text = getString(R.string.word_count,0, MAX_NO_OF_WORDS)
// 데이터흐름을 관찰하기 위해 로그를 붙여넣음
viewModel.currentScrambledWord.observe(viewLifecycleOwner) {
newWord ->
binding.textViewUnscrambledWord.text = newWord
Log.d(GameFragment::class.java.name, "newWord - observe : $newWord")
}
viewModel.score.observe(viewLifecycleOwner){
newScore ->
binding.score.text = getString(R.string.score, newScore)
Log.d(GameFragment::class.java.name, "newScore - observe : $newScore")
}
viewModel.currentWordCount.observe(viewLifecycleOwner){
newWordCount->
binding.wordCount.text = getString(R.string.word_count,newWordCount, MAX_NO_OF_WORDS)
Log.d(GameFragment::class.java.name, "newWordCount - observe : $newWordCount")
}
...
}
...
}
[부연설명] viewLifeCycleOwner란?
Androidx 1.1.0(2019년 9월) 부터 추가된 클래스입니다.
공식가이드에 따르면,
이 변수는 Fragment의 생명 주기를 그대로 따라갑니다.하지만, Fragment가 detached 된 상태이면, Fragment는 View의 생명 주기보다 길어질 수 있습니다.
실제 구현한 것은 인터페이스 입니다. lifecycleOwner 인터페이스의 구현체를 통해, 개발자가 구현한 클래스들이 라이프사이클의 변화를 감지하고, 사용할 수 있습니다. 이 구현체를 이용하면 개발자의 코드 내부에는 Activity나 Fragment를 전부 구현할 필요 없습니다.
[환경]
IDE : Android Studio Flamingo | Android Studio 2022.2.1 Patch (Help메뉴 > About 항목 클릭)
언어 : Kotlin 1.8.0 빌드 수준의 build.gradle 파일 참조 ( 안드로이드 프로젝트 경로 > build.gradle > buildscript { ext.kotlin_version 값 }
[reference]
(현재 강의는 내려감)The RED : 강사룡의 앱 안정성 및 확장성 강화를 위한 Android 아키텍처 https://youtu.be/7qnmwpIFebo
ViewModel과 함께 LiveData 사용하기 : https://developer.android.com/codelabs/basic-android-kotlin-training-livedata?hl=ko#0
android-basics-kotlin-unscramble-app의 GitHub 링크 : https://github.com/google-developer-training/android-basics-kotlin-unscramble-app/tree/starter
Medium 참조 글 : https://blog.stackademic.com/long-lasting-mvvm-pattern-explained-on-android-4f7e09c08caa
MVVM Architecture Explained On Android
MVVM is getting more and more popular. What is MVVM? How to use it? Why should you use it? What makes Android ViewModel special?
blog.stackademic.com
안드로이드의 ViewLifeCycleOwner란 : https://developer.android.com/reference/kotlin/androidx/fragment/app/Fragment#getView()
안드로이드 공식가이드
https://developer.android.com/reference/kotlin/androidx/lifecycle/LifecycleOwner
LifecycleOwner | API reference | Android Developers
developer.android.com
안드로이드의 lifecycleOwner 인터페이스 선언
[도움]
1. 응원 댓글은 글 쓰는데 힘이 됩니다.
2. 공감도 글 쓰는데 힘이 됩니다.
3. 광고 한번 클릭해 주시면 힘은 두 배가 됩니다.
4. 혹시라도 부족한 부분이 있다면 덧글로 남겨주세요. 남기시면, 더 나은 글을 쓸 재료가 됩니다.
'Kotlin' 카테고리의 다른 글
[코루틴] 효율적이고, 빠른 경험을 주는 동시성(Concurrent) 구현하기. (0) | 2025.05.26 |
---|---|
[코루틴] 윈도 어플리케이션 실전 사용을 위한 준비물 2 (0) | 2025.05.24 |
[코루틴] 윈도 어플리케이션 실전 사용을 위한 준비물 1 (0) | 2025.05.03 |
[코루틴]작업 캔슬하지 못하게 하기 (0) | 2025.04.30 |
1. 실전 MVVM 합니다. (2) | 2025.04.08 |