Skip to content

Commit

Permalink
REFACTOR/#19: LoginViewModel에서 LoginRepository 사용
Browse files Browse the repository at this point in the history
  • Loading branch information
youjin09222 committed Jun 7, 2024
1 parent 02d5575 commit 544dc83
Showing 1 changed file with 17 additions and 41 deletions.
Original file line number Diff line number Diff line change
@@ -1,51 +1,27 @@
package com.sopt.now.compose.presentation

import android.util.Log
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.sopt.now.compose.data.BaseState
import com.sopt.now.compose.data.ServicePool
import androidx.lifecycle.viewModelScope
import com.sopt.now.compose.core.view.UiState
import com.sopt.now.compose.data.UserPreference
import com.sopt.now.compose.data.dto.request.RequestLoginDto
import com.sopt.now.compose.data.dto.response.ResponseAuthDto
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import com.sopt.now.compose.data.repository.LoginRepository
import kotlinx.coroutines.launch

class LoginViewModel : ViewModel() {
private val authService by lazy { ServicePool.authService }
val liveData = MutableLiveData<BaseState>()
val userIdLiveData = MutableLiveData<String?>()
class LoginViewModel(
private val loginRepository: LoginRepository,
private val userPreference: UserPreference
) : ViewModel() {
private val _postLoginLiveData: MutableLiveData<UiState<ResponseAuthDto>> = MutableLiveData()
val postLoginLiveData: LiveData<UiState<ResponseAuthDto>> = _postLoginLiveData

fun login(request: RequestLoginDto) {
authService.login(request).enqueue(object : Callback<ResponseAuthDto> {
override fun onResponse(
call: Call<ResponseAuthDto>,
response: Response<ResponseAuthDto>,
) {
if (response.isSuccessful) {
val data: ResponseAuthDto? = response.body()
val userId = response.headers()["location"]
userIdLiveData.value = userId
liveData.value = BaseState(
isSuccess = true,
message = "로그인 성공! 유저의 ID는 $userId 입니다."
)
Log.d("Login", "data: $data, userId: $userId")
} else {
val error = response.message()
liveData.value = BaseState(
isSuccess = false,
message = "로그인 실패 $error"
)
}
}

override fun onFailure(call: Call<ResponseAuthDto>, t: Throwable) {
liveData.value = BaseState(
isSuccess = false,
message = "서버 에러"
)
}
})
fun postLogin(request: RequestLoginDto) {
viewModelScope.launch {
val result = loginRepository.postLogin(request)
_postLoginLiveData.value = result
}
}
}

0 comments on commit 544dc83

Please sign in to comment.