I need to get an Observer event when the item is added to the List of LiveData. But as far as I understand the event receives only when I replace the old list with a new one
How about this?
public class ListLiveData<T> extends LiveData<List<T>> {
public void addAll(List<T> items) {
if (getValue() != null && items != null) {
getValue().addAll(items);
setValue(getValue());
}
}
public void clear() {
if (getValue() != null) {
getValue().clear();
setValue(getValue());
}
}
@Override public void setValue(List<T> value) {
super.setValue(value);
}
@Nullable @Override public List<T> getValue() {
return super.getValue();
}
}
// add changed listener
mMessageList.observe(mActivity, new Observer() {
@Override public void onChanged(@Nullable Object o) {
notifyDataSetChanged();
}
});
I think this class will help you:
class ArrayListLiveData<T> : MutableLiveData<ArrayList<T>>()
{
private val mArrayList = ArrayList<T>()
init
{
set(mArrayList)
}
fun add(value: T)
{
mArrayList.add(value)
notifyChanged()
}
fun add(index: Int, value: T)
{
mArrayList.add(index, value)
notifyChanged()
}
fun addAll(value: ArrayList<T>)
{
mArrayList.addAll(value)
notifyChanged()
}
fun setItemAt(index: Int, value: T)
{
mArrayList[index] = value
notifyChanged()
}
fun getItemAt(index: Int): T
{
return mArrayList[index]
}
fun indexOf(value: T): Int
{
return mArrayList.indexOf(value)
}
fun remove(value: T)
{
mArrayList.remove(value)
notifyChanged()
}
fun removeAt(index: Int)
{
mArrayList.removeAt(index)
notifyChanged()
}
fun clear()
{
mArrayList.clear()
notifyChanged()
}
fun size(): Int
{
return mArrayList.size
}
}
and this extensions:
fun <T> MutableLiveData<T>.set(value: T)
{
if(AppUtils.isOnMainThread())
{
setValue(value)
}
else
{
postValue(value)
}
}
fun <T> MutableLiveData<T>.get() : T
{
return value!!
}
fun <T> MutableLiveData<T>.notifyChanged()
{
set(get())
}