在没有LifecycleOwner的自定义视图中设置LiveData观察器

问题描述 投票:6回答:1

我正在尝试使用新的Android架构组件,并且在尝试将MVVM模型用于自定义视图时遇到了障碍。

基本上我已经创建了一个自定义视图来封装一个公共UI,它是在整个应用程序中使用的相应逻辑。我可以在自定义视图中设置ViewModel但是我必须使用observeForever()或在自定义视图中手动设置LifecycleOwner,如下所示,但似乎都不正确。

选项1)使用observeForever()

活动

class MyActivity : AppCompatActivity() {

    lateinit var myCustomView : CustomView

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        myCustomView = findViewById(R.id.custom_view)
        myCustomView.onAttach()
    }

    override fun onStop() {
        myCustomView.onDetach()
    }
}

自定义视图

class (context: Context, attrs: AttributeSet) : RelativeLayout(context,attrs){

    private val viewModel = CustomViewModel()

    fun onAttach() {
        viewModel.state.observeForever{ myObserver }
    }

    fun onDetach() {
        viewModel.state.removeObserver{ myObserver }
    }
}

选项2)从Activity`设置lifecycleOwner

活动

class MyActivity : AppCompatActivity() {

    lateinit var myCustomView : CustomView

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        myCustomView = findViewById(R.id.custom_view)
        myCustomView.setLifeCycleOwner(this)
    }
}

自定义视图

class (context: Context, attrs: AttributeSet) : RelativeLayout(context,attrs){

    private val viewModel = CustomViewModel()

    fun setLifecycleOwner(lifecycleOwner: LifecycleOwner) {
        viewModel.state.observe(lifecycleOwner)
    }
}

我只是在滥用模式和组件吗?我觉得应该有一种更简洁的方法从多个子视图中组合复杂的视图,而不必将它们绑定到Activity / Fragment

android mvvm android-architecture-components android-livedata android-viewmodel
1个回答
2
投票

1选项 - 出于好意,你仍然需要做一些手工工作 - 比如,调用onAttach \ onDetach架构组件的主要目的是防止这样做。

2选项 - 在我看来更好,但我认为将你的逻辑绑定在ViewModelView上有点不对。我相信你可以在Activity/Fragment中做同样的逻辑而不将ViewModel和LifecycleOwner传递给CustomView。单一方法updateData就足够了。

因此,在这种特殊情况下,我会说它过度使用架构组件。

© www.soinside.com 2019 - 2024. All rights reserved.