Updating MutableLiveData<ArrayList<User>>

50 views Asked by At

Until now I have been changing User in MutableLiveData<ArrayList<User>> by deleting and adding User(with updated attributes)

Is there any other option to update a User in ArrayList of MutableLiveData<ArrayList<User>>?

1

There are 1 answers

0
M Riaz On

If you want to update a user in the ArrayList within a MutableLiveData, you don't necessarily need to delete and re-add the user. You can follow these steps:

Assuming you have a MutableLiveData<ArrayList> named userListLiveData

Step 1: Retrieve the current list

val currentList = userListLiveData.value ?: arrayListOf()

Step 2: Find the user to update

val userToUpdate = currentList.find { it.id == userId }

Replace userId with the ID of the user you want to update.

Step 3: Update the attributes of the user

userToUpdate?.apply {
    // Update user attributes here
    name = "New Name"
    // Update other attributes as needed...
}

Step 4: Update the MutableLiveData with the modified list

userListLiveData.value = currentList