SignUpViewModel.kt 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. package com.vpn.fastestvpnservice.viewmodels
  2. import android.util.Log
  3. import androidx.lifecycle.LiveData
  4. import androidx.lifecycle.MutableLiveData
  5. import androidx.lifecycle.ViewModel
  6. import com.google.gson.Gson
  7. import com.google.gson.reflect.TypeToken
  8. import com.vpn.fastestvpnservice.beans.DataResponse
  9. import com.vpn.fastestvpnservice.beans.UserResponse
  10. import com.vpn.fastestvpnservice.retrofit.RetrofitNetworkHandling
  11. import com.vpn.fastestvpnservice.retrofit.WebServiceFactory
  12. import retrofit2.Call
  13. import retrofit2.Callback
  14. import retrofit2.Response
  15. class SignUpViewModel: ViewModel() {
  16. var mutableLiveData = MutableLiveData<DataResponse<UserResponse>?>()
  17. var liveDataSignUp: LiveData<DataResponse<UserResponse>?> = mutableLiveData
  18. var mutableLiveDataStatus = MutableLiveData<Boolean>()
  19. var mutableLiveDataMessage = MutableLiveData<String>()
  20. private var mutableLiveDataSignUpStatus = MutableLiveData<Boolean>(false)
  21. var liveDataSignUpStatus: LiveData<Boolean> = mutableLiveDataSignUpStatus
  22. fun signUp(email: String, password: String) {
  23. WebServiceFactory.getInstance().signup(email, password, "no-name")
  24. .enqueue(RetrofitNetworkHandling<Any?>(object :
  25. RetrofitNetworkHandling.ResponseCallback<Any?>{
  26. override fun onSuccess(call: Call<Any?>?, response: Any?) {
  27. Log.d("test_api_response", "signup::")
  28. try {
  29. val gson = Gson()
  30. val jsonString = gson.toJson(response)
  31. val type = object : TypeToken<DataResponse<UserResponse>>() {}.type
  32. val data = gson.fromJson<DataResponse<UserResponse>>(jsonString, type)
  33. Log.d("test_api_response", "signup:: ${data.status}")
  34. data.let {
  35. mutableLiveData.value = data
  36. }
  37. } catch (ex: Exception) {
  38. Log.d("test_api_response", "signup:: catch")
  39. mutableLiveDataSignUpStatus.value = false
  40. mutableLiveData.value = null
  41. }
  42. }
  43. override fun onFail(call: Call<Any?>?, response: Any?) {
  44. Log.d("test_api_response", "signup:: onFail")
  45. mutableLiveData.value = null
  46. mutableLiveDataSignUpStatus.value = false
  47. }
  48. override fun onError(call: Call<Any?>?, response: Any?) {
  49. Log.d("test_api_response", "signup:: onError")
  50. mutableLiveData.value = null
  51. mutableLiveDataSignUpStatus.value = false
  52. }
  53. }))
  54. }
  55. fun setSignUpStatus(status: Boolean) {
  56. mutableLiveDataSignUpStatus.value = status
  57. }
  58. }