I declared variable like this.
var saleData: MutableLiveData<SaleData> = MutableLiveData()
data class
data class SaleData(
var saleType: Int,
var saleDetail: Int,
var salePrice: Int,
var saleRate: Int,
var printAmount: Int
)
and then, init the data
init {
saleData.value = SaleData(saleType = 1, saleDetail = 0, salePrice = 0, saleRate = 0, printAmount = 1)
}
The question is, if one of the components of the data class in SaleData changes, can I be notified of this?
I simply wrote the code as below, but there was no result value.
viewModel
fun changeData() {
saleData.value?.saleRate = 50
}
fragment – at onCreateView
binding.viewModel = viewModel
binding.lifecycleOwner = this
viewModel.saleData.observe(viewLifecycleOwner, Observer { saleData ->
Log.d(TAG,"value changed")
})
I can’t get the Log when change the saleRate in saleData
Like this code,
saleData.value = SaleData(saleType = saleType, saleDetail = 0, salePrice = 0, saleRate = 0, printAmount = 1)
I set saleData value, it notify the value changed but I want when change the item of saleData, notify the change
Is there anything else I need to set up?
2
Answers
A call to
saleData.value?.saleRate = 50
will not notify observers because the underlying object stored within theMutableLiveData
remains unchaged. ForLiveData
to notify its observers, you need to assign a new object to it.Assuming
SaleData
is a data class, you can make it notify it’s observers by calling,saleData.value = saleData.value?.copy(saleRate = 50)
This will notify all registered observers.
As Rafsanjani said, you need to assign an updated reference of the SaleData class to the LiveData. Once you do that, the LiveData observer will notify the changes. For better understanding, please, see the code below.
SaleDataViewModel
SaleDataFragment