I have a general question about App architecture with Android. I am implementing an App (in Java) that has a single activity and 20Fragments (that are similar but not the same). So far I implemented everything in the fragments (UI, Logic, Database queries). Now I am considering to use a ViewModel but I am not sure whether it is worth the effort. So my question is whether each of my 20 Fragments should have an own ViewModel or whether I can just implement one ViewModel for all the 20 Fragments? Implementing a ViewModel for all Fragment classes would drastically increase the effort, so I would like to know if it is possible to have only one ViewModel for all Fragments?
It is technically possible to have one ViewModel for all Fragments.
However, since this one ViewModel would have to manage a number of very different use cases, it would be something like a god object. With 20 Fragments, it would have very many lines of code ...
Switching over to MVVM is generally worth the effort becasue in the long run the app is easier to test and to maintain.
It may be a good idea to have a BaseViewModel in your app: a ViewModel class which handles things which are similar in all use cases, like letting the Fragment know that it should show a loading indicator or an error message. The "normal" ViewModels could extend BaseViewModel and focus on their use cases.
It makes sense in some cases to have a shared ViewModel, for example when a Fragment shows a dialog with some EditTexts or when one has workflow with a sequence of 3-4 Fragments on a small device where on a larger device one or two Fragments would suffice.
Just in case, here's my favourite starting point for MVVM app architecture: Guide to app architecture
Have one view model for each fragment. This way each viewmodel is responsible for doing something related to one fragment and so testing is also easier.
In fact you can have multiple view models for a single fragments doing different things for you.
Keeping everything in one view model would make testing harder and also you have to keep viewmodel for all 20 fragments may be scoping to activity.
Now I am considering to use a ViewModel but I am not sure whether it
is worth the effor
This is definitely worth it if you want good for future development.
So my question is whether each of my 20 Fragments should have an own
ViewModel or whether I can just implement one ViewModel for all the 20
Fragments?
Each fragment should have its own ViewModel, I don't appreciate sharing ViewModel. I develop a lot of apps and what I've come to realize is that I should try to avoid tight coupling. Because every time you develop there will be a lot of changes and when you edit or add or remove it will make you edit a lot because the links are too tight. It would be nice to take them apart and still be able to run normally and when needed to be able to reassemble them like putting together puzzle pieces.
Implementing a ViewModel for all Fragment classes would drastically
increase the effort, so I would like to know if it is possible to have
only one ViewModel for all Fragments?
possible if you want, in programming nothing is impossible. But if you do, you shouldn't because it will only make your code more complicated.
You can read more about the model here.
https://developer.android.com/jetpack/guide#overview
You can go through with this link
Shareable ViewModel
This is pretty much easy with Kotlin by using extention function, But In Java, we need to create a function for creating ViewModel and handle their scope according to the lifecycle of activity/fragment.
Related
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.
I have a project with 1 main activity and 4 fragments all inheriting from the same "BaseFragment".
When first started I managed the whole project with the same ViewModel all through the main activity and fragments but after a while, the code inside became too extensive and decided to split it in multiple ViewModels according to the necessities of each fragment/activity.
I created one "MainViewModel" and used it in the main activity and the rest of the ViewModels inherit from it.
My question is if it is a good practice for reducing the code in the ViewModel? is it perhaps inefficient to have multiple view models?
what other ways are preferred to simplify it?
Separation of concerns is almost never a bad thing. Ideally, each file/class should be responsible for one thing.
Additionally, you never know how the code will grow. Things tend to only get more complex over time, not usually simpler. So, while having multiple viewModels right now may feel like overkill, it will likely pay off later.
One case where a shared viewmodel between several fragments is ideal is when the fragments need to communicate with each other - they all would then use the activity viewmodel.
I would assume in this case you can use both approaches, though I have never done it, so I can't say for certain.
I'm rewriting a simple application to use the MVVM architecture. I got everything working, except retaining state when the user rotates the screen (or any configuration change for that matter).
While doing research I've come across several options, but I can't figure out which one is right (if there even is only one "right" way).
(onSaveInstanceState: can't be used in the ViewModel, this only works in activities/fragments)
Extending the ViewModel class. This is apparently made to make it easier to store UI-related data across the lifecycle. I find it quite confusing, and it seems overkill for what my app does. There are no async requests to online databases, feeds, or whatsoever. More than that: I can't use #Bindable anymore, so I don't know how to make the binding with my View.
Using fragments to persist state. This is used in Google's own todo-mvvm-databinding sample. I find it strange to use Fragments for this. They don't seem to be made for the purpose of just storing data.
Which one is the "best"? And why?
All the reasons I can find for using Fragments in Android activities have to do with having the ability to display multiple classes/view in the same screen, encapsulating multiple logical components, etc.
Considering all this, it seems, fragments are only actually useful when you employ the use of many of them.
Is that so? Is there ever a point of using just one fragment in an activity?
I ask now because I saw an option on Android Studio to do just that, and I am wondering what the point is.
Out of my personal opinion, I would say yes.
For the following reasons:
Assuming you are familiar with Fragments, creating a Fragment is hardly any extra work plus has the following benefits
Fragments can easily be reused somewhere else (possibly another Activity that has more Fragments, furthermore, Fragments do not necessarily need to use up the full screen).
Activity transitions are more expensive, Fragment transitions are more sophisticated.
The Fragment animation framework is better (in terms of usability and performance).
I always like to keep the number of Activities to a minimum which keeps the AndroidManifest.xml short and clean.
UI separated into Fragments leads to cleaner code structure and easier code maintenance.
According to google coding guidelines, it is best practice to create as few Activities as possible, and create multiple Fragments instead that are switched inside an Activity.
Well it depends, if you are going to use that fragment in another activity yea, you have a "point" and maybe in a future you can reuse it on another activity, but in the case for example of a splash screen well, it don't have a point. All depend in the uses you want to give to your application.
Pros:
-> reusable piece of code
easy to utilize it again in any module
easy to debug
-> handles orientation changes better than activity using setRetainInstance(true)
-> great help when scale the app in future for multipane layouts or multi-screen support
Cons:
-> little overhead and time consuming if you are not familiar with fragments
I'm currently attempting to convert my existing Android app to using Fragments. The main work that my activity does can sometimes take a while, so I implemented some Threads to act as callback handlers - I was led to believe this is best practice to use these and a progress dialog.
Hopefully that makes sense.
My question is: should I move those inner classes to my Fragment class, or keep them in my Activity class?
That depends how many fragments you have and what you're trying to do with those threads. While there is no general rule, here are two things to consider in making your decision.
(1) If you're doing something like downloading information that's going to be used in multiple fragments (say in a ViewPager or Tab set up) it might make sense to have the callbacks in your FragmentActivity this way you can easly distribute that information to the Fragment that will be handling the UI. Another example that comes to mind would be fetching location data. If the location data is going to be used throughout the app, and your FragmentActivity is hosting multiple fragments, it makes more sense to get the information in one place and simply update the fragments individually.
(2) If you're using something like AsyncTask for one-off downloads, posts, or other things unique to a specific fragment, there's nothing wrong with keeping it localized to that fragment. In fact, in that case, it would be less efficient to off load the task to your FragmentActivity than to complete the task localy.
Really there's not "right" answer. Just a question of how your app is structured and what you're trying to acomplish.
Actually the best practice for software in general is a little different, first of all you need to know that there's no "Hard Rules" to anything in software, the keyword is "All Depends(Taken from book Pragmatic Thinking and Learning)" and as such, it all depends on what you want and what you need, you should put things on a balance to know where is better for you, but going back to the best practice in general for these cases the best is to have a Business Model Class completely decoupled from either Fragment/Activity or any other android component, you are actually supposed to have a Model Class and together with a Controller Class, both of them should manipulate/populate the data and views within those elements...
Hope this helps.
Regards!
There's no hard and fast rule, but I like keep them in the scope within which they most naturally fit. If the result of a long running task is only useful within the fragment which initiated it then it lives in the fragment. If the task may affect multiple fragments then it might live in the activity.