Моя цель - захватить или получить ответ из моей viewModel в мой фрагмент signUp, когда я нажимаю кнопку signUp и перехожу к фрагменту проверки , если response.status имеет значение true .
Когда я нажимаю на кнопку регистрации в моем signUpFragment, выполняется запрос на модернизацию POST-запроса, и получается ответ :
UserResponse(message=Sign up successful. A verfication code has been sent to your email address, payload=UserPayload(country=Nigeria, createdAt=2020-04-10T10:55:06.220Z, email=osehiproductengineer@gmail.com, id=5e90508a455f70002f19b42e, isVerified=false, name=osehiase ehilen, phone=07083372454, updatedAt=2020-04-10T10:55:06.220Z, v=0), status=200, token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiI1ZTkwNTA4YTQ1NWY3MDAwMmYxOWI0MmUiLCJpYXQiOjE1ODY1MTYxMDYsImV4cCI6MTU4NjYwMjUwNn0.H_JhBQY-3PQ6Kqk7SS0cm8RP_1mzYlD987M66_LT0PU)
I видел этот ответ, используя журнал; ответ не доходит до моего фрагмента подписи.
Вот мой код репозитория ниже:
class NetworkRepository(): BaseRepository() {
val userApi = UserAPI()
val authAPI = AuthAPI()
val treeAPI = TreeAPI()
val paymentAPI = PaymentAPI()
val loginAPI = LoginAPI()
val TAG = "NETWORK REPOSITORY"
private val _networkState = MutableLiveData<NetworkState>()
val networkState: LiveData<NetworkState>
get() = _networkState
//User
suspend fun createUser(userBody: UserBody): UserResponse {
var status = UserResponse()
// Log.d("SIGNUP_RESPONSE2", "inside status:$status")
withContext(Dispatchers.IO){
try {
status = userApi.addUserAsync(userBody).await()
// Log.d("signup_Response3", "after the call:$status")
}catch (t: Throwable){
Log.e(TAG, t.message.toString())
}
}
Log.d("SIGNUP_RESPONSE", "here is the $status")
return status
}
}
Вот мой код viewModel:
class UserViewModel : ViewModel(){
private val repository = NetworkRepository()
private val job = Job()
private val scope = CoroutineScope(job + Dispatchers.Main)
fun createUser(userBody: UserBody):UserResponse {
var userPayload: UserResponse = UserResponse()
// Log.d("USERVIEWMODEL_TOP", "the first response:$userPayload")
scope.launch {
// userPayload = repository.createUser(userBody)
userPayload = repository.createUser(userBody)
// Log.d("USERVIEWMODELCHCK", "speak now:$userPayload")
}
// Log.d("USERVIEWMODEL_RESPONSE", "check this userViewModelRes:$userPayload")
return userPayload
}
}
Вот Код моего регистрационного фрагмента:
class SignUpFragment : Fragment() {
private lateinit var viewModel: UserViewModel
private lateinit var userBody: UserBody
var captureStatus:UserResponse = UserResponse()
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
viewModel = ViewModelProvider(this).get(UserViewModel::class.java)
return inflater.inflate(R.layout.fragment_sign_up, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
signup_submit_btn.setOnClickListener {
val response = sendUser()
// Log.d("SIGNUP_FRAGMENTRES", "where is this response:$response")
if (response.status == 200) {
Log.d("SIGNUP_FRAGMENT", "wat is here:${response}")
saveUserInfo(response)
findNavController().navigate(R.id.action_signUpFragment_to_verificationFragment)
} else {
Toast.makeText(
this.context,
"${response.status}, ${response.message}",
Toast.LENGTH_SHORT
).show()
}
}
signup_have_an_account.paintFlags = Paint.UNDERLINE_TEXT_FLAG
signup_have_an_account.setOnClickListener {
findNavController().navigate(R.id.action_signUpFragment_to_loginFragment)
}
signup_back_btn.setOnClickListener {
findNavController().popBackStack()
}
}
private fun sendUser(): UserResponse {
var userBody: UserBody? = null
//verification
when {
signup_email_input.editText!!.text.isEmpty() -> {
signup_email_input.editText!!.error = "Email cannot be empty"
}
signup_phone_input.editText!!.text.isEmpty() -> {
signup_phone_input.editText!!.error = "Phone cannot be empty"
}
signup_country_input.editText!!.text.isEmpty() -> {
signup_country_input.editText!!.error = "Country cannot be empty"
}
signup_password_input.editText!!.text.isEmpty() -> {
signup_password_input.editText!!.error = "Password cannot be empty"
}
signup_password_input.editText!!.text.length < 6 -> {
signup_password_input.editText!!.error = "Password cannot be less than 6 characters"
}
signup_name_input.editText!!.text.isEmpty() -> {
signup_name_input.editText!!.error = "Name cannot be empty"
}
else -> {
val email = signup_email_input.editText!!.text.toString()
val country = signup_country_input.editText!!.text.toString()
val name = signup_name_input.editText!!.text.toString()
val password = signup_password_input.editText!!.text.toString()
val phone = signup_phone_input.editText!!.text.toString()
userBody = UserBody(country, email, false, name, password, phone)
}
}
// Log.d("USER REG", userBody.toString())
return viewModel.createUser(userBody!!)
}
private fun saveUserInfo(userResponse: UserResponse) {
this.activity?.let { Preferences.setEmail(it, userResponse.payload!!.email) }
this.activity?.let { Preferences.saveAuthToken(it, userResponse.token!!) }
}
}