Skip to content

Commit

Permalink
#26 Feat: MypageViewModel runCatching으로 변경
Browse files Browse the repository at this point in the history
  • Loading branch information
0se0 committed Jun 6, 2024
1 parent 81b98d3 commit e552454
Showing 1 changed file with 36 additions and 21 deletions.
57 changes: 36 additions & 21 deletions app/src/main/java/com/sopt/now/ui/mypage/MypageViewModel.kt
Original file line number Diff line number Diff line change
Expand Up @@ -2,40 +2,55 @@ package com.sopt.now.ui.mypage

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.sopt.now.data.UserRepository
import com.sopt.now.network.response.ResponseInfoDto
import com.sopt.now.network.response.UserInfo
import com.sopt.now.network.service.ServicePool
import com.sopt.now.ui.AuthState
import retrofit2.Call
import retrofit2.Callback
import kotlinx.coroutines.launch
import retrofit2.Response

class MypageViewModel(private val userRepository: UserRepository): ViewModel() {
class MypageViewModel(private val userRepository: UserRepository) : ViewModel() {
private val authService by lazy { ServicePool.authService }
val userInfoStatus = MutableLiveData<AuthState>()
private val userInfoStatus = MutableLiveData<AuthState>()
val userLiveData = MutableLiveData<UserInfo?>()

fun info() {
authService.info().enqueue(object : Callback<ResponseInfoDto> {
override fun onResponse(call: Call<ResponseInfoDto>, response: Response<ResponseInfoDto>) {
if (response.isSuccessful) {
val userInfo = response.body()?.data
if (userInfo != null) {
userLiveData.postValue(userInfo)
userInfoStatus.value = AuthState(isSuccess = true, message = "회원 정보 조회 성공")
} else {
userInfoStatus.value = AuthState(isSuccess = false, message = "회원 정보 없음")
}
} else {
userInfoStatus.value = AuthState(isSuccess = false, message = "회원 정보 조회 실패")
}
viewModelScope.launch {
runCatching {
authService.info()
}.onSuccess { response ->
handleSuccess(response)
}.onFailure {
userInfoStatus.value = AuthState(
isSuccess = false,
message = "서버 에러"
)
}
}
}

override fun onFailure(call: Call<ResponseInfoDto>, t: Throwable) {
userInfoStatus.value = AuthState(isSuccess = false, message = "서버 에러")
}
})
private fun handleSuccess(response: Response<ResponseInfoDto>) {
if (response.isSuccessful) {
successResponse(response)
} else {
failResponse()
}
}

private fun successResponse(response: Response<ResponseInfoDto>) {
val userInfo = response.body()?.data
if (userInfo != null) {
userLiveData.postValue(userInfo)
userInfoStatus.value = AuthState(isSuccess = true, message = "회원 정보 조회 성공")
} else {
userInfoStatus.value = AuthState(isSuccess = false, message = "회원 정보 없음")
}
}

private fun failResponse() {
userInfoStatus.value = AuthState(isSuccess = false, message = "회원 정보 조회 실패")
}

fun logout() {
Expand Down

0 comments on commit e552454

Please sign in to comment.