Search code examples
androidrepository-patternandroid-livedataandroid-mvvm

Repository pattern is not correctly returning LiveData


I am using MVVM, LiveData and trying and implement Repository pattern.

But, calling a method in my repository class - RegisterRepo which returns LiveData is not working. I have no idea why. Any suggestions would be greatly appreciated.

Boilerplate code is removed for breivity.

Activity' s onCreateMethod

mViewModel.status.observe(this, Observer {
            when (it) {
                true ->  {
                    Log.d("----------", " true ") //These message is never being printed. 
                }
                false -> {
                    Log.d("----------", "false ") //These message is never being printed. 

                }
            }
        })

button.setOnClickListener {
   mViewModel.a()
}

ViewModel

class AuthViewModel (val repo: RegisterRepo): ParentViewModel() {
   //...

    var status = MutableLiveData<Boolean>()
    fun a() {
        status = repo.a()
    }
}

RegisterRepo

class RegisterRepo () {

fun a(): MutableLiveData<Boolean> {
        var result = MutableLiveData<Boolean>()
        result.value = true

        return result
    }

}

However, if I change my code in ViewModel to this, everything is working fine.

ViewModel

class AuthViewModel (val repo: RegisterRepo): ParentViewModel() {
   //...

    var status = MutableLiveData<Boolean>()
    fun a() {
        status.value = true //Change here causing everything work as expected. 
    }
}


Solution

  • In the first ViewModel code, when method a is called, you assign another LiveData to status variable, this live data is different from the one observed by the Activity, so that the value won't be notify to your Activity