简体   繁体   English

将 LifecycleObserver 与 ViewModel 一起使用是一种好习惯吗

[英]Is it a good practice to use LifecycleObserver with ViewModel

I am using LifecycleObserver with ViewModel and it is working fine but is it a good practice to use LifecycleObserver with ViewModel ?我将LifecycleObserverViewModel一起使用,它工作正常,但是将LifecycleObserverViewModel一起使用是一种好习惯吗?

ViewModel.kt视图模型.kt

class ViewModel() :ViewModel(), LifecycleObserver 
{
    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    fun startTimer() {

    }

    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    fun stopTimer() {

    }
}

Fragment.kt片段.kt

class Fragment : Fragment()
{
    private val viewModel: ViewModel by lazy {
        ViewModelProviders.of(this).get(ViewModel::class.java)
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View?
    {
        val binding = DataBindingUtil.inflate(inflater, R.layout.fragment_people, container, false)

        viewLifecycleOwner.lifecycle.addObserver(viewModel)

        return binding.root
    }
}

Well, architecture component is specifically designed to place everything where everything should be, cause it follows the Separation of Concern .好吧,架构组件专门设计用于将所有内容放在应有的位置,因为它遵循关注点分离
-> ViewModel we don't define lifecycle inside the viewmodel, because that's what viewModel does. -> ViewModel我们没有在 viewmodel 中定义生命周期,因为那是viewModel所做的。 But if still there is a case you wanna call any lifeCycle method, ie: onDestroy , onAttach() you would still have to call them inside Activity or Fragment .但是,如果仍然存在您想调用任何lifeCycle方法的情况,即: onDestroyonAttach()您仍然必须在Activity 或 Fragment中调用它们。
-> Repository is meant for fetching the data either to local cache or remote server, but if you skip the repository and somehow directly hop your all code inside the viewModel your code become tightly coupled and it won't no longer be flexible. ->存储库用于将数据获取到本地缓存或远程服务器,但如果您跳过存储库并以某种方式直接将所有代码跳到 viewModel 中,您的代码将变得紧密耦合,并且不再灵活。
Respecting the Separation of Concern gives your code awesome flexibility.尊重关注点分离为您的代码提供了极大的灵活性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM