简体   繁体   中英

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

在第一个 ViewModel 代码中,当方法a被调用时,您将另一个LiveData分配给status变量,此实时数据与Activity观察到的数据不同,因此该值不会通知您的Activity

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM