I am having some common logic which I currently have it in a Util class. Now, I want to move this logic to ViewModel class. As this util method is used in different fragments, is it a good practice to create a common view model (feature based view model) for multiple fragments. I know Google recommended to use 1 view model for 1 view. Please suggest.
Asked
Active
Viewed 2,775 times
4
-
2`ViewModel` should **never** have any logic it just adapts the `Model` to the `View`. It's not used for that purpose. Use your `Util` in every class you need to – Juan Carlos Rodriguez Sep 20 '18 at 15:36
-
Great!, got it now, thanks @juan – Prasanna Narshim Sep 20 '18 at 15:40
2 Answers
1
If you've got common code, you could have several viewModels that inherit from a baseViewModel, which contains the shared code.
The advantage of this over a Util class is that the shared code is only visible to ViewModels that derive from the base, and can't get confused with anything else.

Robin Bennett
- 3,192
- 1
- 8
- 18
-
I assume topic starter wants beside common code to have a shared state too. Due Android platform framework it might be an issue https://stackoverflow.com/questions/67544852/how-to-share-viewmodel-scope-between-a-particular-set-of-fragments-without-usin – Gleichmut Aug 01 '23 at 11:02
1
It's better to create a viewmodel
per each fragment
, but it is possible to create a single viewmodel
for several fragment
s. According to the official documents:
class SharedViewModel : ViewModel() {
val selected = MutableLiveData<Item>()
fun select(item: Item) {
selected.value = item
}
}
class MasterFragment : Fragment() {
private lateinit var itemSelector: Selector
// Use the 'by activityViewModels()' Kotlin property delegate
// from the fragment-ktx artifact
private val model: SharedViewModel by activityViewModels()
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
itemSelector.setOnClickListener { item ->
// Update the UI
}
}
}
class DetailFragment : Fragment() {
// Use the 'by activityViewModels()' Kotlin property delegate
// from the fragment-ktx artifact
private val model: SharedViewModel by activityViewModels()
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
model.selected.observe(viewLifecycleOwner, Observer<Item> { item ->
// Update the UI
})
}
}

Kaaveh Mohamedi
- 1,399
- 1
- 15
- 36