简体   繁体   中英

MVVM architecture with custom view

I want to make a custom view in android with MVVM architecture. First of all, I want to ask, is ViewModel working perfectly with a custom view as it works in case of activity or fragment? Can we get ViewModel from ViewModel provider in a custom view?

If I need to make a separate custom view what will the correct approach?

Q: Can we get ViewModel from ViewModel provider in a custom view?

Ans: Simple answer would be yes you can !

But How? (Further explanation) ViewModelProviders required either context as Activity or Fragment . So you can retrieve context from your CustomView class using getContext() which would be Activity/Fragment where you're using it.

Cast that context to either of type & provide it to ViewModelProviders which will give you object of that Activity/Fragment container.

Hence using like this, you can share ViewModel between your CustomView and Activity/Fragment .


Side Note: You can also make your CustomView implement LifeCycleObserver , in such way you can also make your view respect lifecycle of Activity/Fragment for initialization/destruction stuffs.

A better alternative would be to use the new API view.findViewTreeViewModelStoreOwner() which gives you the viewModelStoreOwner(Fragment if view is attached to the fragment o/w activity)

You can create ViewModelProvider and then get the ViewModel.

Below is an example of code in Kotlin

private val viewModel by lazy(LazyThreadSafetyMode.NONE) {
        ViewModelProvider(viewModelStoreOwner).get(ViewModel::class.java)
}

Similarly, there are other similar APIs like view.findViewTreeLifecycleOwner() and view.findViewTreeSavedStateRegistryOwner()

It is a much cleaner approach as you don't have to typecast your context into Activity or Fragment and will scale to other implementations of ViewModelStoreOwner as well.

One thing to note here is that view may have a shorter life span compared to Activity/Fragment and so you might have to make a custom view Lifecycle(so that your LiveData subscription gets managed properly) using LifecycleRegistry based on onAttachedToWindow and onDetachedFromWindow callbacks

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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