Notify Observer when item is added to List of LiveData

后端 未结 8 1196
一个人的身影
一个人的身影 2020-12-07 20:21

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

8条回答
  •  感情败类
    2020-12-07 20:47

    I think this class will help you:

    class ArrayListLiveData : MutableLiveData>()
    {
        private val mArrayList = ArrayList()
    
        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)
        {
            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  MutableLiveData.set(value: T)
        {
            if(AppUtils.isOnMainThread())
            {
                setValue(value)
            }
            else
            {
                postValue(value)
            }
        }
    
        fun  MutableLiveData.get() : T
        {
            return value!!
        }
    
        fun  MutableLiveData.notifyChanged()
        {
            set(get())
        }
    

提交回复
热议问题