Azizjon Kholmatov
Azizjon Kholmatov

Reputation: 1256

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. 
    }
}

Upvotes: 0

Views: 116

Answers (2)

Sahjad Ansari
Sahjad Ansari

Reputation: 110

the 2nd way is correct to use and it will work fine the 1st is not working because you are creating new MutableLive data in your RegisterRepo, so basically at the time your create an observable to "status" is deferent where you assign a value into it is different. so the second one is the only way to do this

Upvotes: 1

Duy Khanh Nguyen
Duy Khanh Nguyen

Reputation: 509

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

Upvotes: 2

Related Questions