如何在MutableLiveData中观察类的成员变量?

时间:2019-02-17 22:03:44

标签: android mvvm kotlin android-architecture-components

我试图在不暴露课堂的情况下观察我课堂的内容。到目前为止,我已经尝试过:

TaskItemViewModel.kt

open class TaskItemViewModel(private val navigator: ITaskNavigator) : ViewModel() {

    private val taskItem: MutableLiveData<TaskItem> = MutableLiveData()

    val title: LiveData<String?> = Transformations.map(taskItem) { it.title }

    val content: LiveData<String?> = Transformations.map(taskItem) { it.content }

    var showCheck: LiveData<Boolean> = Transformations.map(taskItem) { it.isCompleted }

    fun setModel(model: TaskItem) {
        this.taskItem.value = model
    }
}

ItemListScreenAdapter.kt

class ItemListScreenAdapter(private val navigator: ITaskNavigator) : RecyclerView.Adapter<ItemListScreenAdapter.TaskItemViewHolder>() {
    private val TAG = "ItemListScreenAdapter"
    private var dataset: List<TaskItem> = listOf()

    override fun onBindViewHolder(viewHolder: TaskItemViewHolder, position: Int) {
            with(viewHolder.binding) {
            this.viewModel?.setModel(dataset[position])
            executePendingBindings()
        }
    }

    fun updateDataset(dataset: List<TaskItem>) {
        Log.d(TAG,"Updating dataset")
        this.dataset = dataset
        notifyDataSetChanged()
    }

    override fun getItemCount(): Int = dataset.size

    override fun onCreateViewHolder(parent: ViewGroup, type: Int): TaskItemViewHolder {
        val inflater = LayoutInflater.from(parent.context)
        val binding = ItemTaskBinding.inflate(inflater, parent, false)
        binding.viewModel = TaskItemViewModel(navigator)
        return TaskItemViewHolder(binding)
    }

    class TaskItemViewHolder(val binding: ItemTaskBinding) : RecyclerView.ViewHolder(binding.root)
}

如果我在放大视图之前调用setModel,则一切正常。但是,将视图放大后,即使taskItem的值已更新,也不会更新视图。您可以放心,每次数据集更改时都会调用updateDataset

我希望每当在相应的视图模型中调用setModel时,视图都将更新。有什么方法可以做到这一点?

对于此视图模型,我想使用ViewModel而不是BaseObservable。因此,请据此给出答案。

编辑: 我找到了解决问题的方法。

ItemListScreenAdapter的{​​{1}}方法中,膨胀后,我需要设置onCreateViewHolder的绑定。

在膨胀ItemTaskBinding之后,我添加了以下行。

LifeCycleOwner

问题已解决,视图正在更新。

0 个答案:

没有答案