Notify Observer when item is added to List of LiveData

后端 未结 8 1197
一个人的身影
一个人的身影 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:28

    Inspired by @user3682351 here is my solution. It seems that we cannot update properties of a LiveData value individually so the value must be updated on each operation. This is essentially a small wrapper on live data with convenience methods for modifying properties of a HashMap

    import androidx.lifecycle.LiveData
    
    /**
     * Hash Map Live Data
     *
     * Some convenience methods around live data for HashMaps. Putting a value on this will also update the entire live data
     * as well
     */
    class HashMapLiveData : LiveData>() {
    
        /**
         * Put a new value into this HashMap and update the value of this live data
         * @param k the key
         * @param v the value
         */
        fun put(k: K, v: V) {
            val oldData = value
            value = if (oldData == null) {
                hashMapOf(k to v)
            } else {
                oldData.put(k, v)
                oldData
            }
        }
    
        /**
         * Add the contents to the HashMap if there is one existing, otherwise set the value to this HashMap and update the
         * value of this live data
         * @param newData the HashMap of values to add
         */
        fun putAll(newData: HashMap) {
            val oldData = value
            value = if (oldData != null) {
                oldData.putAll(newData)
                oldData
            } else {
                newData
            }
        }
    
        /**
         * Remove a key value pair from this HashMap and update the value of this live data
         * @param key the key to remove
         */
        fun remove(key: K) {
            val oldData = value
            if (oldData != null) {
                oldData.remove(key)
                value = oldData
            }
        }
    
        /**
         * Clear all data from the backing HashMap and update the value of this live data
         */
        fun clear() {
            val oldData = value
            if (oldData != null) {
                oldData.clear()
                value = oldData
            }
        }
    
        var value: HashMap?
            set(value) = super.setValue(value)
            get() = super.getValue()
    
    }
    
    

提交回复
热议问题