ListAdapter获取正确的列表,但不更新值

问题描述

我具有以下功能-

    private fun fetchGroupData(callback: (groupModelList: List<GroupModel>) -> Unit) {
        val groupModelList = mutablelistof<GroupModel>()
        groupviewmodel.getAllGroupEntities().observeOnce(requireActivity(),Observer { groupEntityList ->
            groupEntityList.forEach { groupEntity ->
                /*
                We iterate though all of the available groups,for each group we get all of it's groupMembers models
                */
                val groupName = groupEntity.groupName
                val groupId = groupEntity.id
                taskviewmodel.getGroupTaskCounter(groupId).observeOnce(requireActivity(),Observer { groupTaskCount ->
                    /*
                    For each group we observe it's task counter
                     */
                    groupviewmodel.getGroupMembersForGroupId(groupId).observeOnce(requireActivity(),Observer { groupMembers ->
                        /*
                        For each group,we iterate through all of the groupMembers and for each of them we use it's userId
                         to fetch the user model,getting it's full name and adding it to a list of group users full name.
                         */
                        val groupUsersFullNames = mutablelistof<String>()
                        groupMembers.forEach { groupMember ->
                            val memberId = groupMember.userId
                            groupviewmodel.getGroupParticipantForUserId(memberId).observeOnce(requireActivity(),Observer { groupUser ->
                                groupUsersFullNames.add(groupUser.fullName)
                                /*
                                When the groupUsersFullNames size matches the groupMembers size,we can add a model to our list.
                                 */
                                if (groupUsersFullNames.size == groupMembers.size)
                                    groupModelList.add(GroupModel(groupId,groupName,groupTaskCount,groupUsersFullNames))
                                /*
                                When the new list matches the size of the group list in the DB we call the callback.
                                 */
                                if (groupModelList.size == groupEntityList.size)
                                    callback(groupModelList)
                            })
                        }
                    })
                })
            }
        })
    }

以下功能正在使用-

 private fun initAdapter() {
        fetchGroupData { groupModelList ->
            if (groupModelList.isEmpty()) {
                binding.groupsListNoGroupsMessageTitle.setAsVisible()
                binding.groupsListNoGroupsMessageDescription.setAsVisible()
                return@fetchGroupData
            }
            binding.groupsListNoGroupsMessageTitle.setAsGone()
            binding.groupsListNoGroupsMessageDescription.setAsGone()
            val newList = mutablelistof<GroupModel>()
            newList.addAll(groupModelList)
            adapter.submitList(groupModelList)
            Log.d("submitList","submitList")
            binding.groupsListRecyclerview.setAdapterWithItemdecoration(requireContext(),adapter)
        }
    }

这2个函数代表从本地DB到RecyclerView中的组列表获取

为了在创建新组时收到通知,我持有一个共享的viewmodel对象,该对象带有一个布尔值,指示是否已创建新组。

在编写这两个函数^的同一片段中,我正在观察此布尔值,如果该值为true,则会触发整个列表的重新提取-

private fun observeSharedinformation() {
        sharedinformationviewmodel.value.groupCreatedFlag.observe(requireActivity(),Observer { hasGroupBeenCreated ->
            if (!hasGroupBeenCreated) return@Observer
            sharedinformationviewmodel.value.groupCreatedFlag.value = false
            Log.d("submitList","groupCreatedFlag")
            initAdapter()

        })
    }

在我代码的某个片段中的某个点上,该片段中也有我的共享viewmodel的实例,我触发了Boolean LiveData的值更改-

sharedinformationviewmodel.value.groupCreatedFlag.value = true

依次触发观察者,并重新获取我的群组列表。

我面临的问题是,在重新获取新列表时(因为已添加了新组),我确实获得了当前信息,并且一切都应该可以正常工作,但新数据-新创建的组-不会出现。

在2种情况下,新添加的数据均显示在列表中-

  1. 我重新启动应用
  2. 功能再次被触发-现在发生的是,我看到具有先前新添加的组的列表,但是没有出现要添加的最新组。

此问题有一个例外-如果组列表为空,则当我与一个组一起提交列表时,确实会出现第一个添加的组。

我想念什么?

编辑-

这是我的适配器。

我正在使用一个名为DefaultAdapterDiffUtilCallback的自定义调用,该调用需要一个模型,该模型实现一个为每个模型定义唯一ID的接口,以便我可以比较新模型和旧模型。

class Groupslistadapter(
    private val context: Context,private val onClick: (model : GroupModel) -> Unit
) : listadapter<GroupModel,GroupsListViewHolder>(DefaultAdapterDiffUtilCallback<GroupModel>()) {

    override fun onCreateViewHolder(parent: ViewGroup,viewType: Int): GroupsListViewHolder {
        val binding = GroupsListViewHolderBinding.inflate(LayoutInflater.from(context),parent,false)
        return GroupsListViewHolder(binding)
    }

    override fun onBindViewHolder(holder: GroupsListViewHolder,position: Int) {
        holder.bind(getItem(position),onClick)
    }

    override fun submitList(list: List<GroupModel>?) {
        super.submitList(list?.let { ArrayList(it) })
    }
}


/**
 * Default DiffUtil callback for lists adapters.
 * The adapter utilizes the fact that all models in the app implement the "ModelWithId" interfaces,so
 * it uses it in order to compare the unique ID of each model for `areItemsTheSame` function.
 * As for areContentsTheSame we utilize the fact that Kotlin Data Class implements for us the equals between
 * all fields,so use the equals() method to compare one object to another.
 */
class DefaultAdapterDiffUtilCallback<T : ModelWithId> : DiffUtil.ItemCallback<T>() {
    override fun areItemsTheSame(oldItem: T,newItem: T) =
        oldItem.fetchId() == newItem.fetchId()

    @SuppressLint("DiffUtilEquals")
    override fun areContentsTheSame(oldItem: T,newItem: T) =
        oldItem == newItem
}

/**
 * An interface to determine for each model in the app what is the unique ID for it.
 * This is used for comparing the unique ID for each model for abstracting the DiffUtil Callback
 * and creating a default general one rather than a new class for each new adapter.
 */
interface ModelWithId {
        fun fetchId(): String
}


data class GroupModel(val id: String,val groupName: String,var tasksCounter: Int,val usersFullNames: List<String>) : ModelWithId {

    override fun fetchId(): String = id
}


edit 2.0-

我的observeOnce()扩展名-

fun <T> LiveData<T>.observeOnce(lifecycleOwner: LifecycleOwner,observer: Observer<T>) {
    observe(lifecycleOwner,object : Observer<T> {
        override fun onChanged(t: T?) {
            observer.onChanged(t)
            removeObserver(this)
        }
    })
}

解决方法

您是否正在使用“新” ListAdapter

import androidx.recyclerview.widget.ListAdapter

在这种情况下,我可以想出您的问题的答案。但是由于我不知道您的确切实现,因此它是基于我的假设,因此您必须验证它是否适用。

为此ListAdapter,您必须实现areItemsTheSameareContentsTheSame方法。 我曾经有过类似的问题。我正在提交列表,但是它只是没有更新视图中的列表。

我可以通过仔细检查内容是否相同来进行比较来解决此问题。

对于比较功能,请考虑以下因素:

    override fun areContentsTheSame(oldItem: GroupModel,newItem: GroupModel): Boolean {
        // assuming GroupModel is a class
        // this comparison is most likely not getting the result you want
        val groupModelsAreMatching = oldItem == newItem // don't do this
        
        // for data classes it usually gives the expected result
        val exampleDataClassesMatch = oldItem.dataClass == newItem.dataClass
        // But: the properties that need to be compared need to be declared in the primary constructor
        // and not in the function body

        // compare all relevant custom properties
        val groupIdMatches = oldItem.groupId == newItem.groupId
        val groupNameMatches = oldItem.groupName == newItem.groupName
        val groupTaskCountMatches = oldItem.groupTaskCount == newItem.groupTaskCount
        val groupUsersFullNamesMatches = oldItem.groupUsersFullNames == newItem.groupUsersFullNames

        return groupIdMatches && groupNameMatches && groupTaskCountMatches && groupUsersFullNamesMatches
}

当然,您需要确保areItemsTheSame。在这里,您只需要比较groupIds。

您已经这样做了吗?

,

我发现了问题。

它与我的提取逻辑无关。

问题出在下面-

创建组时,我要向后堆栈中添加一个新的Fragment,并在完成后将其弹出。

删除群组时,我正在导航至我的主要片段,同时使用popUpTopopUpToInclusive-效果很好。

我需要使用导航,而不是向后弹出堆栈以查看新列表。

这花了我3天的时间来弄清楚。 jeez