4

Question

Cutting right to the chase: In Android development, is it good or bad practice to inject (ActivityScoped) LiveData instances into ViewModels using Hilt in order to observe the live data from multiple fragments?

Are there any major downsides to this approach, and is there a better way of achieving the same behavior? We could consider moving a portion or all of the code from the fragment view models to the activity view model, as the dependencies would suggest this is a better approach to begin with, but this would end up making the activity view model quite big.

Background

And some background, in case this helps to answer the question:

I have been working on an Android application in which we are using Hilt for dependency injection, Android's MVVM architecture components, and our interpretation of clean architecture which is more or less based on this article: https://www.raywenderlich.com/3595916-clean-architecture-tutorial-for-android-getting-started

Our app contains two activities and a couple of fragments, and each have been assigned their own view model. Recently as the application has grown, the code base has become a bit messy, partly due to many fragments (and their view models) depending on the same live data. The repositories and data sources injected into the view models are generally singleton, and so data sharing is not an issue.

However, what has happened is that we keep references to all view models in one activity, and many fragments are observing LiveData from each others' view models in order to update their views. This feels like a sub-optimal approach, and we are moving into refactoring season quite soon which will give us the opportunity to fix this.

Filip Östermark
  • 311
  • 2
  • 15
  • why would we observe the LIveData from an Activity inside its fragments ViewModels? If the change happens in the activity or its view model then we will just observe it in fragments through (requireActivity() as YourActivity).LiveDataRefrence.observe(viewLifecycleOwner){ } – aya salama Aug 15 '22 at 04:36
  • Also considering the ViewlModels, Views can have multiple view models, so I would create a Single Shared ViewModel that contains the shared code in interest and include it at all Fragments besides their own specific viewModels! Or if it's a simple process executed in the activity, I would use the approach I wrote in previous comment! DI as a concept is mainly for Decoupling dependencies and injecting a LiveData object won't cause such an issue from my POV – aya salama Aug 15 '22 at 04:40
  • Check this resource for more content about DI https://stackoverflow.com/questions/130794/what-is-dependency-injection?page=1&tab=modifieddesc#tab-top Also LiveData is built upon Observable patters where there's no physical dependency "code writing based " over the object, we're just listening to it's notifications ... Waiting for more inputs from you or fellow devs – aya salama Aug 15 '22 at 04:43

0 Answers0