karteek thati
karteek thati

Reputation: 96

Unable to observe changes in Mutable Live data List

In my Data class I am having

var education: MutableLiveData<ArrayList<DocRegEducation>> =  
MutableLiveData(ArrayList<DocRegEducation>()),

in fragment i am adding value

 docViewModel.doctorRegisterModel.value?.education?.value?.add(doc_reg_edu)

and observing

 docViewModel.doctorRegisterModel.value?.education?.observe(viewLifecycleOwner, Observer {
            it?.let {
                logd("reached education changes observed")
                educationAdapter.setData(it) }
        })

but the changes are not observed

Upvotes: 0

Views: 2737

Answers (2)

DeePanShu
DeePanShu

Reputation: 1326

In ViewModel:

val educationList = ArrayList<DocRegEducation>()
val educationListState = MutableLiveData<Long>(0L)


fun setNewData(data:DogRegEducation){
// adding data for list here
educationList.add(data);
// changing state with respect to time value to observe on view side
educationListState.value = System.currentTimeMillis()

}

On View Side:

docViewModel.educationListState.observe(viewLifecycleOwner, Observer {
               
   // update the adapter on state change when item is added
   educationAdapter.setData(docViewModel.educationList) 
})

Upvotes: 2

Boobalan
Boobalan

Reputation: 823

It's a very common problem for all new Kotlin developers (including me). Here, the array reference is still the same. So, you have to create a new array for each element change and post it again.

Here is the example.

private val _lstAvailability: MutableLiveData<List<AppointmentsItem>> =
        MutableLiveData(emptyList()) 

// Create new mutable list reference
val duplicateList: MutableList<AppointmentsItem> = mutableListOf()

// add all possible AppointmentsItem info here like
duplicate.add(AppointmentsItem("item1"))
duplicate.add(AppointmentsItem("item2"))
duplicate.add(AppointmentsItem("item3"))

// Copy the old items into duplicate list, if needed
_lstAvailability.value.forEach {duplicateList.add(it.copy())}


//Finally update your livedata with new reference
_lstAvailability.value = duplicateList

Upvotes: 1

Related Questions