12

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?

Vinit Saxena
  • 683
  • 2
  • 11
  • 27
  • The Architecture Components ViewModels are made to work with Activities and Fragments, not with the lifecycle of a View, but if you want you can check these articles: 1. https://medium.com/@matthias.c.siegmund/mvvm-architecture-for-custom-views-on-android-b5636cb6be26 2. https://medium.com/@polson55/how-to-use-a-viewmodel-with-a-custom-view-403420f7aab4 – MrVasilev Sep 04 '19 at 14:19

3 Answers3

13

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

AndroidEngineX
  • 975
  • 1
  • 9
  • 22
7

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.

Jeel Vankhede
  • 11,592
  • 2
  • 28
  • 58
  • `ViewModelProviders.of(context)` no longer exists in the newest version. How do I do this using the replacement (`ViewModelProvider()` that takes a `LifecycleOwner`)? – Hannes Hertach Aug 05 '20 at 13:09
  • Yes, that's tricky now. To consume it via `context` you'll need to cast it to `LifecycleOwner` for `ViewModelProvider`. And on custom view, getting context will always be of Activity you're inflating to. – Jeel Vankhede Aug 05 '20 at 13:22
-1
CustomView: ViewModelStoreOwner{

  private var viewModel: YourViewModel

  override fun getViewModelStore() = ViewModelStore() 

  init{
    viewModel = ViewModelProvider(this)[YourViewModel::class.java]
  }

}

that's it :)

Selim SIMSEK
  • 1
  • 1
  • 2
  • 1
    Remember that Stack Overflow isn't just intended to solve the immediate problem, but also to help future readers find solutions to similar problems, which requires understanding the underlying code. This is especially important for members of our community who are beginners, and not familiar with the syntax. Given that, **can you [edit] your answer to include an explanation of what you're doing** and why you believe it is the best approach? – Jeremy Caney Mar 14 '23 at 01:16