Android ViewModel 与 LiveData 的使用场景

更新日期: 2022-11-25 阅读次数: 3127 字数: 273 分类: Android

概述

  • 在 activity 中监听 ViewModel 中数据的变化,当有变化时,将对应的数据显示在界面组件上
  • LiveData 在 ViewModel 中使用,上面监听的数据类型就是 LiveData 类型。
  • 同时可用于 Activity 及 Fragment 间的数据共享

使用逻辑

  • 在 activity 内新建一个 ViewModel,监听数据变化
  • 当有数据变化时,在回调中,更新 UI View 的展示
  • ViewModel 内部则类似微信小程序的 data,里面定义一堆变量,监听的就是这些变量的变化,然后通过 postValue, setValue 这种类似小程序 setData 的操作,来触发后续操作。

ViewModel 与 DataBinding 的关系

既然有了 ViewModel 的实现,为何还需要 DataBinding 呢?

实际上,ViewModel 诞生于 DataBinding 之后,是后出现的概念。

使用 DataBinding 结合 ViewModel 可以在 Layout XML 中写出跟微信小程序 WXML 一样的简洁描述。

参考:

https://developer.android.com/codelabs/android-databinding#2

// Bind the name property of the viewmodel to the text attribute
android:text="@{viewmodel.name}"
// Bind the nameVisible property of the viewmodel to the visibility attribute
android:visibility="@{viewmodel.nameVisible}"
// Call the onLike() method on the viewmodel when the View is clicked.
android:onClick="@{() -> viewmodel.onLike()}"

参考

  • 简洁易懂 https://zhuanlan.zhihu.com/p/93214596

tags: LiveData ViewModel

关于作者 🌱

我是来自山东烟台的一名开发者,有敢兴趣的话题,或者软件开发需求,欢迎加微信 zhongwei 聊聊, 查看更多联系方式