네트워크 연결 성공, 실패를 한 곳에 묶어서 관리하기 위해 정리를 해야한다.
val authService = getRetrofit().create(AuthRetrofitInterface::class.java)
authService.signUp(getUser()).enqueue(object: Callback<AuthResponse>{
override fun onResponse(call: Call<AuthResponse>, response: Response<AuthResponse>) {
val resp:AuthResponse = response.body()!!
when(resp.code)
{
1000 -> {
Log.d("signUp", resp.message)
finish() // 현 activity를 종료
}
2016, 2018 -> {
binding.signUpEmailErrorTv.visibility = View.VISIBLE
binding.signUpEmailErrorTv.text = resp.message
}
}
}
override fun onFailure(call: Call<AuthResponse>, t: Throwable) {
TODO("Not yet implemented")
}
})
따라서 이 코드를 모듈화하는 과정을 글에서 설명할 것이다.
signUpView interface를 생성해서 그 안에 onSignUpSuccess(), onSignUpFailure() 함수를 선언한다.
package com.example.dologinout
interface SignUpView {
fun onSignUpSuccess()
fun onSignUpFailure()
}
이 인터페이스를 SignUpActivity가 상속받아 사용한다.
package com.example.dologinout
class AuthService {
private lateinit var signUpView: SignUpView
fun setSignUpView(signUpView: SignUpView){
this.signUpView = signUpView
}
}
SignUpView를 받을 변수를 만들어주기 위해 함수를 만들어준다.
또한 이전에 만든 signUp()를 통해서 받아온 AuthResponse 데이터 클래스를 enqueue push back을 통해 넣어주는 코드를 이용해 API를 호출, 관리하는 함수를 만들어준다.
fun signUp(user : User)
{
val authService = getRetrofit().create(AuthRetrofitInterface::class.java)
authService.signUp(user).enqueue(object: Callback<AuthResponse> {
override fun onResponse(call: Call<AuthResponse>, response: Response<AuthResponse>) {
val resp:AuthResponse = response.body()!!
when(resp.code)
{
1000 -> signUpView.onSignUpSuccess()
else -> signUpView.onSignUpFailure()
}
}
override fun onFailure(call: Call<AuthResponse>, t: Throwable) {
Log.d("SIGNUP/FAILURE", t.message.toString())
}
})
}
위의 1~2 과정을 통해 아래의 코드를
val authService = getRetrofit().create(AuthRetrofitInterface::class.java)
authService.signUp(getUser()).enqueue(object: Callback<AuthResponse>{
override fun onResponse(call: Call<AuthResponse>, response: Response<AuthResponse>) {
val resp:AuthResponse = response.body()!!
when(resp.code)
{
1000 -> {
Log.d("signUp", resp.message)
finish() // 현 activity를 종료
}
2016, 2018 -> {
binding.signUpEmailErrorTv.visibility = View.VISIBLE
binding.signUpEmailErrorTv.text = resp.message
}
}
}
override fun onFailure(call: Call<AuthResponse>, t: Throwable) {
TODO("Not yet implemented")
}
})
아래의 코드로 모듈화 하였다.
val authService = AuthService() // SignUpView를 받는 변수 선언
authService.setSignUpView(this)
authService.signUp(getUser())
더 관리하기 쉽다.