4

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.

Prasanna Narshim
  • 778
  • 10
  • 14

2 Answers2

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 fragments. 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