Reputation: 873
How can i update a field of a ListItem?
I have following POJO and ViewModel classes. Currently i am getting the complete list from LiveData object and then updating its data then re-setting the value of LiveData object, But I don't think this is the correct way to do it because to update just name of a single book i have to reset the complete LiveData Object.
Any other suggestion or Good practice to do it the correct way?
public class Book {
private long id;
private String name;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public class BookProvider extends AndroidViewModel {
private final MutableLiveData<List<Book>> booksData;
public BookProvider(@NonNull Application application) {
super(application);
booksData = new MutableLiveData<>();
}
public LiveData<List<Book>> getBooksData() {
return booksData;
}
public void updateBookName(int position, String name) {
final List<Book> books = booksData.getValue();
if (books != null && books.size() > position) {
books.get(position).setName(name);
}
booksData.setValue(books);
}
}
Upvotes: 5
Views: 5271
Reputation: 3454
LiveData
is just a container holding a reference to your data and notifying possible observer of changes. So as far as LiveData
is concerned this is the best you can do.
However LiveData
does't support molecular changes so every change may results in the entire list invalidating and redrawn. It is strongly suggested that you use a different method if you have lot of changes in data (like real-time applications).
Upvotes: 2