Notify Observer when item is added to List of LiveData

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

    LiveData will only notify when its wrapped object reference is changed. When you assign a new List to a LiveData then it will notify because its wrapped object reference is changed but if add/remove items from a LiveData's List it will not notify because it still has the same List reference as wrapped object. So you can overcome this problem by making an extension of MutableLiveData as follows:

    fun  MutableLiveData>.addNewItem(item: T) {
        val oldValue = this.value ?: mutableListOf()
        oldValue.add(item)
        this.value = oldValue
    }
    
    fun  MutableLiveData>.addNewItemAt(index: Int, item: T) {
        val oldValue = this.value ?: mutableListOf()
        oldValue.add(index, item)
        this.value = oldValue
    }
    
    fun  MutableLiveData>.removeItemAt(index: Int) {
        if (!this.value.isNullOrEmpty()) {
            val oldValue = this.value
            oldValue?.removeAt(index)
            this.value = oldValue
        } else {
            this.value = mutableListOf()
        }
    }
    

    Then add/remove items from your MutableLiveData like:

    // Here is your IssuePost list
    var issuePostList = MutableLiveData>()
    
    // Add new item to your list
    issuePostList.addNewItem(IssuePost(UserEntity(name, email, photoUrl), issueEntity))
    
    // Delete an item from your list at position i
    issuePostList.removeItemAt(i)
    
    // Add new item to your list at position i
    issuePostList.addNewItemAt(i, IssuePost(UserEntity(name, email, photoUrl), issueEntity))
    

提交回复
热议问题