Created
June 6, 2025 08:30
-
-
Save acious/39130a7ac21ec906c396d01120cc1e9d to your computer and use it in GitHub Desktop.
C.C - Presentaion Layer
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // file: presentation/UserViewData.kt | |
| import java.util.Calendar | |
| /** | |
| * UI에 표시하기 위해 가공된 데이터 클래스. | |
| * Entity와 달리, UI에 필요한 형태로 포맷팅된 텍스트나 상태를 가집니다. | |
| */ | |
| data class UserViewData( | |
| val displayName: String, // 예: "이름: 홍길동" | |
| val age: String, // 예: "나이: 30세" | |
| val contactInfo: String // 예: "연락처: gdhong@example.com" | |
| ) | |
| // file: presentation/UserViewModel.kt | |
| import androidx.lifecycle.ViewModel | |
| import androidx.lifecycle.viewModelScope | |
| import kotlinx.coroutines.flow.MutableStateFlow | |
| import kotlinx.coroutines.flow.StateFlow | |
| import kotlinx.coroutines.launch | |
| import java.util.Calendar | |
| class UserViewModel(private val getUserUseCase: GetUserUseCase) : ViewModel() { | |
| private val _userState = MutableStateFlow<UserViewState>(UserViewState.Loading) | |
| val userState: StateFlow<UserViewState> = _userState | |
| fun fetchUser(userId: String) { | |
| viewModelScope.launch { | |
| _userState.value = UserViewState.Loading | |
| getUserUseCase(userId) | |
| .onSuccess { userEntity -> // UseCase로부터 순수 Entity를 받음 | |
| // Entity를 UI에 맞는 ViewData로 변환 | |
| _userState.value = UserViewState.Success(userEntity.toViewData()) | |
| } | |
| .onFailure { error -> | |
| _userState.value = UserViewState.Error(error.message ?: "알 수 없는 오류") | |
| } | |
| } | |
| } | |
| /** | |
| * Mapper 확장 함수: Domain Entity를 Presentation용 ViewData로 변환합니다. | |
| * 이 로직은 Presentation 계층에 속합니다. | |
| */ | |
| private fun User.toViewData(): UserViewData { | |
| val currentYear = Calendar.getInstance().get(Calendar.YEAR) | |
| val calculatedAge = currentYear - this.birthYear + 1 | |
| return UserViewData( | |
| displayName = "이름: ${this.name}", | |
| age = "나이: ${calculatedAge}세", | |
| contactInfo = "연락처: ${this.email}" | |
| ) | |
| } | |
| } | |
| // UI 상태를 나타내는 Sealed Class | |
| sealed class UserViewState { | |
| object Loading : UserViewState() | |
| data class Success(val userData: UserViewData) : UserViewState() | |
| data class Error(val message: String) : UserViewState() | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment