簡體   English   中英

將 LifecycleObserver 與 ViewModel 一起使用是一種好習慣嗎

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

我將LifecycleObserverViewModel一起使用,它工作正常,但是將LifecycleObserverViewModel一起使用是一種好習慣嗎?

視圖模型.kt

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

    }

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

    }
}

片段.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
    }
}

好吧,架構組件專門設計用於將所有內容放在應有的位置,因為它遵循關注點分離
-> ViewModel我們沒有在 viewmodel 中定義生命周期,因為那是viewModel所做的。 但是,如果仍然存在您想調用任何lifeCycle方法的情況,即: onDestroyonAttach()您仍然必須在Activity 或 Fragment中調用它們。
->存儲庫用於將數據獲取到本地緩存或遠程服務器,但如果您跳過存儲庫並以某種方式直接將所有代碼跳到 viewModel 中,您的代碼將變得緊密耦合,並且不再靈活。
尊重關注點分離為您的代碼提供了極大的靈活性。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM