For what other purposes we can use ViewModel for?
I have been asked if an Activity is locked to portrait mode, then is this relevant to use ViewModel?
If Yes why?
In general, ViewModel is an architectural component that "couples" a view with a model. From the architectural point of view it is relevant.
Additionally to the general component, Android Jetpack's ViewModel is also lifecycle-aware. You can treat it as a conveniency bonus.
With that being said, if the app is not supposed to have configuration changes (screen rotation is one of those) you may use any CustomViewModel.
Related
Hello devs I have one questions I hope you can help me.
I have read that Google recommends having a View Model for each screen, a screen could communicate with the View Model to perform many different actions. So the View Model would have many responsibilities, which is against the S of solid. Would it be good to have the necessary View Models for each screen so that each one has a single responsibility?
This multiple View Model approach I believe would improve reusability, encapsulation, and fragmentation; since if two screens need to do the same action, there is no need to duplicate the code of the corresponding View Models or pass the same use case to both. Each screen would access what you need.
You have asked a great question.
These are just my opinion:
You mentioned multiple ViewModels for one screen(let's say 'view') and the Single Responsibility Principle.
1: Yes you can use multiple ViewModels for a view. But it is not typical in MVVM structure.
2: The main purpose of ViewModel is to separate your concern and can test the logic of the app without launching the device or emulator(run at JVM level)
3: SRP is not just the way you consider in ViewModels, Let me give you an example: Imagine you want to validate an email or phone, ... in your ViewModel, You can make a class for validation that follows SRP(It has single responsibility), Now you can use this class where you need it in ViewModels. define your shared classes, repositories, or use cases that follow SRP and use them in your ViewModel, Not define multiple viewModels in your views, I believe that each view has its own viewModel.
In android, viewModel also was designed to hold data for views. It means when your configuration changes your activity and fragment's data will not destroy.
Hope this helps you :)
I'm trying to understand why is ActivityRetainedScoped introduced for DI in Hilt. It looks to me that the scope is identical to what ViewModelScoped should do. I was under the impression that scoped worked like this:
AppScope (singleton) > ViewModelScope > ActivityScope > ViewScope > ...
But this graphic kinda hints that ViewModel and Activity scopes are... siblings?
According to the docs:
"ActivityRetainedComponent lives across configuration changes, so it
is created at the first Activity#onCreate() and destroyed at the last
Activity#onDestroy()."
Well, so does the view model, no?
I'm pretty sure view models survive config changes (that's the whole point if having them in the first place)
What is ActivityRetainedScoped? How is it different from VM scope? Why does google likes over complicating things that should be conceptually simple
https://developer.android.com/training/dependency-injection/hilt-android
Well, even tho ActivityRetainedScope and ViewModelScope are Siblings and one could think that makes them the same, there are in fact not.
Well, so does the view model, no? I'm pretty sure view models survive config changes (that's the whole point if having them in the first place)
Well yes, but actually no. A Viewmodel does survive configuration changes, but only of its scoped lifecyleowner. So let's think of the following scenario:
You have two dependencies, one is ActivtyRetainedScoped and the other one is viewmodelscoped.
When you now inject the viewmodeldependency inside the viewmodel and the lifecycleowner of the viewmodel is an activity, then you are right, both the ActivtyRetainedScope and the ViewmodelScope would not make any difference.
But now let's assume the lifecycleowner is a fragment, in this case, the viewmodelscoped dependency would "die" when you navigate out of the fragment and the activtyretainedscope dependency would outlive the viewmodelscoped one.
I hope I could explain the difference between them both. Kinda hard with those "scopes" etc. when English is not your native language. Also, I am not 100% if this is the correct answer
Google states to use SharedViewModel in case of communication between Fragments by scoping it to the activity.
In a Single Activity Application, this means that the activity will be littered with ViewModels which might not be needed anymore and they will stay there for the whole lifecycle. Considering some example like a extended sign up flow or something considering a few screens.
One way recommended was using a parent Fragment as scope, but that is only possible if there is a parent fragment. It can be just different Fragments.
I came up with the following solution, I want to know how viable or how bad is it and is there any better way around?
Considering I have two Fragments called ExampleOneFragment and ExampleTwoFragment for sake of simplicity and I want them to have a shared scope without actually scoping it to the activity. Let's say I want to update text view in ExampleOneFragment from ExampleTwoFragment so I create a SharedViewModel like this for both
For ExampleOneFragment it will be:
private val mSharedViewModel by lazy {
ViewModelProvider(this).get(SharedViewModel::class.java)
}
And For ExampleTwoFragment I came up with this:
private val mSharedViewModel by lazy {
ViewModelProvider(supportFragmentManager().findFragmentByTag(ExampleOneFragment.TAG) ?: this).get(SharedViewModel::class.java)
}
This seems to be working, but I don't know what kind of issues can this cause.
Some Other Solutions are which I found:
According to #mikhehc here We could actually create our very own ViewModelStore instead. This will allow us granular control to what scope the ViewModel have to exist. But I don't understand how to make it work for Fragments?
Secondly, is the hacky way of scoping it to the activity still, but clearing it out via dummy viewmodel by using same key which I found here
Could anyone guide me what is the right approach? I cannot shift to NavGraphs since it is an already up and running project and scoping to activity just feels wrong. Thanks.
This seems to be working, but I don't know what kind of issues can this cause.
This code will only work if:
An ExampleOneFragment is created first, always
It is added to the same FragmentManager that ExampleTwoFragment uses, via a tag of ExampleOneFragment.TAG, always
If either of those assumptions fail, you will wind up with separate viewmodel instances, because supportFragmentManager().findFragmentByTag(ExampleOneFragment.TAG) ?: this will resolve to this.
But I don't understand how to make it work for Fragments?
You would use it the way it is shown in that answer, or by anything else that accepts a ViewModelStoreOwner. In this line:
val viewModel = ViewModelProvider(myApp, viewModelFactory).get(CustomViewModel::class.java)
You would get myApp from your Fragment as:
val myApp = requireContext().application as MyApp
Personally, I think the solution that you pointed to is very risky. The ViewModelStore lives for the entire lifetime of the process and is never cleared. You will wind up sharing your viewmodel across everything, and everything done by that viewmodel is leaked. The concept of creating a custom ViewModelStoreOwner is fine, but you should be doing something to tie the scope of that owner to the relevant lifetime for the viewmodels that it stores. The answer tries to dance around that in its last paragraph; too many developers will ignore this and run into problems.
One way recommended was using a parent Fragment as scope, but that is only possible if there is a parent fragment. It can be just different Fragments.
Your app is not written in a way to make automatic ViewModelStoreOwner management available "out of the box", then.
In the end, you are looking for a ViewModelStoreOwner to be shared between these two fragments. In your first solution, you are trying to hack that by using the ViewModelStoreOwner from one of those fragments, which only works if you can reliably choose which fragment that is. In the solution you pointed to in that other answer, you are trying to hack that by intentionally leaking a ViewModelStoreOwner.
There may be other approaches that you could consider, depending on your circumstances. For example, there may be some option with your dependency inversion framework (Dagger/Hilt, Koin, etc.) to rig up a ViewModelStoreOwner that is tied to a specific pair of fragment instances.
Is there a difference between the "newer" Model-View-Intent architecture compared to the "older" ones like MVC and MVVM?
What issue does MVI address? What are the similarities with MVC/MVVM? What are the differences?
There are similar questions already on stackoverflow for MVC/MVV/MVP but none so far that explains MVI.
What is the difference between MVC and MVVM?
What are MVP and MVC and what is the difference?
from my experience each architecture pattern of those was invented to solve specific problem that the previous one ignored or wasn't observed yet.
MVC - Model View Controller
in UI applications the responsibilty of rendering the data to the screen, or the business logic and bind those together at first wasn't clear. so MVC came to define those responsibility to three components, each one has one purpose, and the picture describe the relation between those three components.
View - is the UI component that has all the properties like color, shape, tools to listen to the click events .. etc.
Model - is the component that define the business logic that you want the view to render and behave accordingly.
Controller - is the one who change the model, so if the view has a name for example to save, View pass it to the controller then controller manipulate the model with the right actions.
MVP - Model view presenter
the problem with MVC that there is a great coupling between the three components, if you want to change the view calls, it will require you to update controller and the Model.
and that's clear from the MVC picture, the relationship between the three components is very tied, you couldn't replace one of those components without the other.
So MVP came to provide a more clean solution to the previous problem by separating the Model and the View, keep the interactions between them via the Presenter, Presenter is the middle man that each the view and the model call.
So if you want to save a list of favorites movies, View listen to user (*) action, then call the presenter function that update the model, then model tells the Presenter if that succeed or not, and Presenter tells the View to show the right message.
MVVM - Model View ViewModel
with the rise of reactive paradigm, it was clear that we can provide more separate of concerns in UI Applications by just observing the changes and behave on it.
so for example there is a click in view that need to call an api to get latest tv shows.
this view click will be observed at the ViewModel, ViewModel interact with the model to get the data, and finally ViewModel post those data on the view using other observer ..
so in short, View observe ViewModel to get UI updates, and ViewModel observe View to call the right action with the Model. Observer pattern has proved his worthy in decoupling logic so here you go a new Pattern.
So after talking about the most popular architecture patterns, each one has tried to decouple the UI code from the business code. but the previous patterns doesn't bound updating UI with different states in the same time.
if you had an issue that related to the loading appear with an error message showed at the same time, you will understand what I'm talking about, so to maintain UI state, you have to do extra effort looking what you wrote wrong causing those kind of issues.
MVI - Model View Intent
MVI is based on an old idea called finite state machine, any system or component has predictable, set of states is a finite state machine.
in MVI any update to the UI is defined by new state, you could find this is overwhelming, but imagine that you have a screenshot for each time UI changes, that's the state. you can debug, test, reproduce the state issues now.
how to achieve this, that's the MVI in practice.
any user interaction with the UI, is defined in MVI by an Intent, Intent is what the user need from this action, it could be star a movie, refresh the screen, it even could be opening the screen, in that case the Intent is an initial intent to show the screen with all required data.
which component get those Intents to act according on them, that what you define .. you could use a Presenter or a ViewModel, it doesn't matter, MVI is more a practices than using a new middle component.
I'll continue with ViewModel, ViewModel will get those intents, decide which usecase to call (Model behaviors).
all usecases pass by summer function in the ViewModel, that decide which state that needs to be reflected to the View, it provides you with previous state too, so you have the previous and the new state to update the screen, which reduce the rendering updates, and View get only the new hints to update itself.
and finally MVI is uni directional flow, it starts with the View and ends with the View.
... View -> ViewModel/Presenter -> Model -> View -> ...
MVI is different in the way of managing the state, it's a combination of several ideas to build more stable, and testable app.
A really great breakdown is here: https://academy.realm.io/posts/mvc-vs-mvp-vs-mvvm-vs-mvi-mobilization-moskala/. At it's core, MVI is taking the ideas of MVVM (stateless UI state), separate business logic and models, and putting the reactive framework on top of it. Making things streams of events instead of discrete actions, making receiving elements consumers of transformed streams instead of presentation elements, and making state a read-only, disposable thing that is acted upon explicitly in a very structured way.
This requires that you take a functional approach to writing your application, especially the UI/View part of things. State is not modified, new state is calculated from an intent and a series of use-cases. This is fairly well explained here: https://proandroiddev.com/mvi-a-new-member-of-the-mv-band-6f7f0d23bc8a.
It is intended to address the growing complexity of modern UI applications, who have a non-trivial amount of client-side state that needs to be managed explicitly. As most experienced programmers know, the most complex failures come from state that is being modified in an unexpected way. This state manipulation can result in "invalid" states that your application cannot handle, which is effectively a crashed application. MVI addresses this by making state transitions explicit and carefully structured so that they system never comes to an invalid state, and the state is always understandable.
I work on rewriting my app to MVVM architecture concept.
Based one my understanding all the business logic should live in the ViewModel and the UI components in the Activity or Fragment. I use a third party library that needs to be initialized with some view's like: MyLibrary instance = new MyLibrary ("key" , imageView, surfaceView) and then doing some manipulations on these views.
What would be the best place and the right way doing that knowing that it's not recommended passing any Android view to the ViewModel and also not the right thing to initialize SDK in the Activity
You have already answered your question. It's the other way around, the ViewModel informs the View (activities and fragment) WHAT should be chaged, and the View simply handles HOW it should be updated.
Most of the business logic however, if we want to be nitpcky, should still remain in the model. The ViewModel only holds the LiveData that the View needs. Some reasons for this is that you don't want your model to be Android architecture dependent. But also to follow the single purpose principle. This way you avoid making the ViewModel into a God object that handles everything. Instead you only allow it to format data, pass commands, provide factory methods for binding
to the viewModel, and subscribing/getting relevant changes from the model.
So in short: The View passes user-input to the ViewModel who issues commands on the Model. The ViewModel then format the changes from the Model and posts the changes using LiveData to the View. The View finally updates the components that the user can see.
Check the example here for how the UI is updated.
https://developer.android.com/topic/libraries/architecture/viewmodel
Read more about the pattern here:
https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93viewmodel