Skip to content

Commit

Permalink
refactor/#9: SignUpViewModel 코루틴으로 변경
Browse files Browse the repository at this point in the history
  • Loading branch information
youjin09222 committed May 24, 2024
1 parent d4cec71 commit 8ca5997
Showing 1 changed file with 14 additions and 44 deletions.
58 changes: 14 additions & 44 deletions app/src/main/java/com/sopt/now/test/presentation/SignUpViewModel.kt
Original file line number Diff line number Diff line change
Expand Up @@ -2,55 +2,25 @@ 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.request.RequestSignUpDto
import com.sopt.now.test.data.dto.response.ResponseAuthDto
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import kotlinx.coroutines.launch

class SignUpViewModel : ViewModel() {
private val authService by lazy { ServicePool.authService }
val liveData = MutableLiveData<BaseState>()
private val _postSignUpLiveData: MutableLiveData<UiState<ResponseAuthDto>> = MutableLiveData()
val postSignUpLiveData: MutableLiveData<UiState<ResponseAuthDto>> = _postSignUpLiveData

fun signUp(request: RequestSignUpDto) {
authService.postSignUp(request).enqueue(object : Callback<ResponseAuthDto> {
override fun onResponse(
call: Call<ResponseAuthDto>,
response: Response<ResponseAuthDto>,
) {
if (response.isSuccessful) {
val userId = response.headers()["location"]
liveData.value = BaseState(
isSuccess = true,
message = "회원가입 성공 유저의 ID는 $userId 입니다."
)
} 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<ResponseAuthDto>, t: Throwable) {
liveData.value = BaseState(
isSuccess = false,
message = "서버 에러"
)
}
})
fun postSignUp(requestSignUp: RequestSignUpDto) {
viewModelScope.launch {
runCatching {
ServicePool.authService.postSignUp(requestSignUp)
}.fold(
{ _postSignUpLiveData.value = UiState.Success(it) },
{ _postSignUpLiveData.value = UiState.Failure(it.message.toString()) }
)
}
}
}

0 comments on commit 8ca5997

Please sign in to comment.