【问题标题】:What is the best way to call fragments method from ViewModel in MVVM architecture using live data使用实时数据从 MVVM 架构中的 ViewModel 调用片段方法的最佳方法是什么
【发布时间】:2021-04-22 06:11:15
【问题描述】:

例如,由于 ViewModel 应该是松耦合的,我们不能将接口引用传递给 ViewModel 以从 Viewmodel 获取回调并调用片段中实现的方法。

还请提供一个示例或参考,以使用 livedata 调用具有两个或多个参数的方法。

【问题讨论】:

    标签: android mvvm android-livedata android-mvvm


    【解决方案1】:

    在 ViewModel 中创建一个实时数据变量,并在 Fragment 中将观察者附加到该变量,只要数据发生变化,就会自动调用该函数。

    例如:

       viewModel.loading.observe(viewLifecycleOwner, { loading ->
            loading?.let {
              // Here, I'm calling a new function named setLoaderVisibility
    
                setLoaderVisibility(loader = binding.shimmerProductDetail, binding.containerBody, isLoaderVisible = loading)
            }
        })
    

    如有不清楚之处,请随时询问。

    【讨论】:

    • 同意,但是如果fragment中的方法有两个或多个参数怎么办,我们需要从viewmodel中调用这个参数化的fragments方法
    • 您需要在viewModel中使用构造函数传递参数,当需要调用片段时传递参数......
    猜你喜欢
    • 2018-08-23
    • 2018-12-19
    • 2013-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-19
    • 1970-01-01
    相关资源
    最近更新 更多