【问题标题】:Android ViewModel LiveData DocumentationAndroid ViewModel LiveData 文档
【发布时间】:2021-07-16 19:37:23
【问题描述】:

我阅读了文档,但在某些方面感到困惑。

ViewModel 对象旨在比视图或 LifecycleOwners 的特定实例化更长寿。这种设计还意味着您可以更轻松地编写测试来覆盖 ViewModel,因为它不了解视图和生命周期对象。 ViewModel 对象可以包含 LifecycleObservers,例如 LiveData 对象。然而,ViewModel 对象绝不能观察生命周期感知可观察对象的变化,例如 LiveData 对象。如果 ViewModel 需要 Application 上下文,例如查找系统服务,它可以扩展 AndroidViewModel 类,并在构造函数中有一个接收 Application 的构造函数,因为 Application 类扩展了 Context。

这部分让我有些困惑

但是,ViewModel 对象绝不能观察生命周期感知可观察对象的更改,例如 LiveData 对象。

这是指这种实现方式吗?

片段

class AboutFragment : Fragment() {

    private lateinit var aboutViewModel: AboutViewModel
    private var _binding: FragmentAboutBinding? = null

    // This property is only valid between onCreateView and
    // onDestroyView.
    private val binding get() = _binding!!

    override fun onCreateView(
            inflater: LayoutInflater,
            container: ViewGroup?,
            savedInstanceState: Bundle?
    ): View {
        aboutViewModel =
                ViewModelProvider(this).get(AboutViewModel::class.java)

        _binding = FragmentAboutBinding.inflate(inflater, container, false)
        val root: View = binding.root

        val textView = binding.aboutTxt

        //Observe changes
        aboutViewModel.text.observe(viewLifecycleOwner, {
            textView.text = it
        })
        return root
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}

视图模型

class AboutViewModel : ViewModel() {

private val _text = MutableLiveData<String>().apply {
    value = "Foobar......"
           
}

fun setText(text: String){ _text.value = text}

val text: LiveData<String> = _text

}

或者这就是他们的意思LiveData&lt;LiveData&lt;Object&gt;&gt;不要这样做?

【问题讨论】:

    标签: android kotlin mvvm android-viewmodel


    【解决方案1】:

    这意味着您永远不应该在视图模型中的 livedata 对象上使用observe,只能像您已经在做的那样在活动/片段中使用

    【讨论】:

    • 你能举个例子吗?
    • 举例
    • 所以observe 内部没有ViewModel 本身?
    • 而不是您的text.observe 在您的片段中,而是在您的视图模型中。那是你不想做的事
    • Dos and Don'ts 示例
    猜你喜欢
    • 1970-01-01
    • 2020-05-17
    • 2021-01-04
    • 2020-07-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-17
    • 2018-05-10
    相关资源
    最近更新 更多