Skip to content

Commit

Permalink
refactor/#9: UserInfoViewModel 코루틴으로 변경
Browse files Browse the repository at this point in the history
  • Loading branch information
youjin09222 committed May 24, 2024
1 parent 80ce0cb commit 9873cc6
Showing 1 changed file with 15 additions and 49 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2,62 +2,28 @@ package com.sopt.now.test.presentation

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.google.gson.Gson
import androidx.lifecycle.viewModelScope
import com.sopt.now.test.core.view.UiState
import com.sopt.now.test.data.ServicePool
import com.sopt.now.test.data.BaseState
import com.sopt.now.test.data.dto.response.ResponseAuthDto
import com.sopt.now.test.data.dto.response.ResponseUserInfoDto
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import kotlinx.coroutines.launch

class UserInfoViewModel : ViewModel() {
private val userService by lazy { ServicePool.userService }
val liveData = MutableLiveData<BaseState>()
val userInfoLiveData = MutableLiveData<ResponseUserInfoDto?>()
private val _getUserInfoLiveData: MutableLiveData<UiState<ResponseUserInfoDto>> = MutableLiveData()
val getUserInfoLiveData: MutableLiveData<UiState<ResponseUserInfoDto>> = _getUserInfoLiveData

init{
userInfo()
getUserInfo()
}

private fun userInfo() {
userService.getUserInfo().enqueue(object : Callback<ResponseUserInfoDto> {
override fun onResponse(
call: Call<ResponseUserInfoDto>,
response: Response<ResponseUserInfoDto>,
) {
if (response.isSuccessful) {
val data: ResponseUserInfoDto? = response.body()
userInfoLiveData.value = data

liveData.value = BaseState(
isSuccess = true,
message = response.message()
)
} else {
val error = response.errorBody()?.string()
val gson = Gson()
try {
val errorResponse = gson.fromJson(error, ResponseAuthDto::class.java)
liveData.value = BaseState(
isSuccess = false,
message = "회원 정보 조회 실패: ${errorResponse.message}" // 에러 메시지 사용
)
} catch (e: Exception) {
liveData.value = BaseState(
isSuccess = false,
message = "회원 정보 조회 실패: 에러 메시지 파싱 실패"
)
}
}
}

override fun onFailure(call: Call<ResponseUserInfoDto>, t: Throwable) {
liveData.value = BaseState(
isSuccess = false,
message = "서버 에러"
)
}
})
fun getUserInfo() {
viewModelScope.launch {
runCatching {
ServicePool.userService.getUserInfo()
}.fold(
{ _getUserInfoLiveData.value = UiState.Success(it) },
{ _getUserInfoLiveData.value = UiState.Failure(it.message.toString()) }
)
}
}
}

0 comments on commit 9873cc6

Please sign in to comment.