기존 회사 소스코드에서는 정확한 디자인패턴을 적용시키고 있지않았는데, 마침 어느정도 프로젝트가 안정화되면서 나 스스로 개발할 수 있는 시간이 주어졌다.
기존 코드에서는 명확하게 정의된 디자인 패턴이 없었어서, 그 시간동안 디자인 패턴중 가장 대중적으로 많이 사용되는 MVVM 패턴을 도입해보기로 결정했다.
MVVM패턴은 크게 세가지 M(model), V(view), VM(viewmodel)로 구분하여 설계하는 디자인 패턴이다.
이렇게 세개의 관심사를 확실히 분리하면서 서로 계층간의 의존성을 낮춰줄 수 있다.

출저 : https://blog.yena.io/studynote/2019/03/16/Android-MVVM-AAC-1.html
MVVM 패턴은 MVC 패턴의 Controller와 View, MVP 패턴의 Presenter와 View 사이의 의존성의 문제를 해결하기 위해 ViewModel이라는 개념을 도입한 것이다.
ViewModel을 도입하면서 가장 차이점을 드러내는 부분은
1. 양방향 통신
2. View와의 의존성 없음 (ViewModel은 View를 참조하지 않음)
3. View와 ViewModel은 1:n 관계를 가질 수 있음
사용자가 주사위를 굴려 화면에 나타내는 간단한 예제를 보자면
data class DiceUiState(
val firstDieValue: Int? = null,
val secondDieValue: Int? = null,
val numberOfRolls: Int = 0,
)
class DiceRollViewModel : ViewModel() {
// Expose screen UI state
private val _uiState = MutableStateFlow(DiceUiState())
val uiState: StateFlow<DiceUiState> = _uiState.asStateFlow()
// Handle business logic
fun rollDice() {
_uiState.update { currentState ->
currentState.copy(
firstDieValue = Random.nextInt(from = 1, until = 7),
secondDieValue = Random.nextInt(from = 1, until = 7),
numberOfRolls = currentState.numberOfRolls + 1,
)
}
}
}
import androidx.activity.viewModels
class DiceRollActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
// Create a ViewModel the first time the system calls an activity's onCreate() method.
// Re-created activities receive the same DiceRollViewModel instance created by the first activity.
// Use the 'by viewModels()' Kotlin property delegate
// from the activity-ktx artifact
val viewModel: DiceRollViewModel by viewModels()
lifecycleScope.launch {
repeatOnLifecycle(Lifecycle.State.STARTED) {
viewModel.uiState.collect {
// Update UI elements
}
}
}
}
}
참고 : https://developer.android.com/topic/libraries/architecture/viewmodel?hl=ko