I am using Retrofit to get data from API. I am doing it in view model like the following:

class RegisterShopViewModel : ViewModel() {
    private val client by lazy { WebServicesApi.getClient }

    private var isShopRegisterSuccessful = MutableLiveData<Pair<Boolean, List<String>>>()

    fun registerShop(shopModel: ShopModel): LiveData<Pair<Boolean, List<String>>> {
            .enqueue(object : Callback<RegisterResponseModel> {
                override fun onFailure(call: Call<RegisterResponseModel>, t: Throwable) {
                    TODO("Not yet implemented")

                override fun onResponse(
                    call: Call<RegisterResponseModel>,
                    response: Response<RegisterResponseModel>
                ) {
                    response.body()?.let {
                        isShopRegisterSuccessful.value =
                            Pair(it.isSuccess, it.errorsList)
        return isShopRegisterSuccessful

and in my view(Activity/Fragment), I am listening for changes like so

       val email = txtShopEmail.text.toString()
       val password = txtShopPassword.text.toString()
       val confirmPassword = txtShopConfirmPassword.text.toString()
       val name = txtShopName.text.toString()

       val shopModel = ShopModel(email, password, confirmPassword, name)

       registerShopViewModel.registerShop(shopModel).observe(this, Observer {

   private fun registerShop(result: Pair<Boolean, List<String>>) {
       if (result.first)
           Toast.makeText(this, "Registered Successfully", Toast.LENGTH_SHORT).show()
           Toast.makeText(this, "error ${result.second}", Toast.LENGTH_SHORT).show()

my questions are:

1 - is it best practice to send the data in ViewModel's function?

2 - in cases of register/ login in which I send a request with data and wait for a response. Is LiveData useful?

if you have any suggestion to improve this code please share it


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.