在RecyclerView中未调用ViewModel onCleared

时间:2018-10-12 14:39:43

标签: android data-binding kotlin android-databinding

我有一个下面带有代码的适配器。问题是,似乎从未为列表项的ViewModel调用ViewModel的onCleared()-Method。 是否需要设置特殊的方法/标志来清除这些ViewModel?

class BaseRecyclerViewViewModelAdapter(
        private val lifecycleOwner: LifecycleOwner
) : RecyclerView.Adapter<BaseRecyclerViewViewModelViewHolder>() {

    var items: List<BaseRecyclerViewItemViewModel> = emptyList()
        set(value) {
            field = value
            notifyDataSetChanged()
        }

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

    override fun getItemCount() = items.size

    override fun onBindViewHolder(holder: BaseRecyclerViewViewModelViewHolder, position: Int) {
        with(holder.binding) {
            setVariable(BR.viewModel, items[position])
            setLifecycleOwner(lifecycleOwner)
            executePendingBindings()
        }
    }

    override fun getItemViewType(position: Int) = items[position].layoutId
}

1 个答案:

答案 0 :(得分:0)

不会。根据官方documentation的说法:

  

所有者活动完成后,框架将调用ViewModel   对象的onCleared()方法,以便清理资源。

如果您想clear列表中的某些内容-您应该手动进行。