In MVVM, is the ViewModel always necessary? - android

I'm new to making android apps, Kotlin, and just trying to get my head around the MVVM design pattern.
I'm attempting to make a login screen while also integrating well with my team's existing code. Making the login screen work went well until I noticed that I was running into life-cycle issues with uninitialized lateinit vars (even though the code definitely ran the initialization statements) like SharedPreferences or the username and password fields etc.
After reading up more on MVVM, I believe that the existing code which I was learning from (which contains lateinit vars for Context, the Fragment, and View within the ViewModel etc) is fundamentally flawed and fails to decouple the ViewModel from the View life-cycle.
However this has me confused. To my understanding, the ViewModel is supposed to contain the business logic and any data which we want to survive configuration changes. On the other hand, the LoginFragment should only contain UI and OS interactions such as displaying the View or capturing input.
The LoginViewModel only contains code interfacing between the elements of fragment_login.xml and SharedPreferences, or logging errors:
resetFields(): empties the fields to blank
onLoginButtonClicked(): just calls the Retrofit function to POST the username/password a server for authentication
onLoginSuccessful(): saves the data to SharedPreferences
onLoginUnsuccessful(): changes the field's error message and logs the error
Because I used DataBinding on the xml elements, nothing (as far as I can tell) needs to be independent of the life-cycle (or rather, several things require access to the context or fragment!).
What is the proper way to go about this? Currently I am thinking that the ViewModel simply shouldn't exist and that all functionality (of which there is very little) should actually just be within LoginFragment). I was considering learning about and using LiveData next, but I just can't see how LiveData or ViewModel are necessary in this situation.

The main goal of any architectural pattern is to achieve Decoupling, Single responsibility and restricting Anti Patterns, to be precise code should be more readable, scalable and easily testable.
I know in some instances using this patterns might seem redundant for your use case, but always keep scaling in mind when ever developing even a simple feature. This will pay off in long term and help peers understand and isolate code better.
In Android, always remember view or UI(Activity/Fragment) should be as dumb as possible, only responsibility of them should be to listen to user touches and display data, by doing so you can test all your logic in isolation without relying on Android Framework.
MVVM is once such pattern designed keeping pain points of Android in mind, it does not cause any harm using it when needed to delegate even simple tasks like storing data to preferences, minor transformations to data before displaying. Let's say you have a static page which just displays static data using String and nothing else then you can avoid ViewModels.
MVVM pattern does not enforce you to use ViewModel for every Fragment/Activity, it recommends using it when needed as a best practice, ViewModel is just a data holder which persists configuration changes.

Related

LiveData Vs StateFlow: Should we switch from Live data to State Flow?

I have come across articles that recommend switching to StateFlow.
Like the one here.
Also in the new Android studio, StateFlow support is automatically included in the functionality of data binding, including the coroutines dependencies.
Live data is already in use in most of the apps.
Should we migrate from LiveData to StateFlow? What are the benefits?
There is not much difference between State Flow and Live Data. The Main difference come in that State Flow requires an Initial value hence no need to check for nullability. The Second Difference come in unregistering the consumer; Live Data does this automatically when the view goes to STOPPED state while State Flow does not. To achieve similar behaviour as Live Data, you can collect the flow in a Lifecycle.repeatOnLifecycle block.
Benefits of State Flow
State flow is included in coroutines library and can be used in Multiplatform Projects
Using one API in your project(Flow), not two (LiveData and Flow).
It's Kotlin, Why Not
It depends on what you want,
If you want a manual, full and versatile control over the app , go for state flow
If you want a partially automatic or relatively easy-to-use method for your app , I will say - stick with live data
In case If you want to know my personal opinion, it's state flow, as i prefer control over easy-to-use. I don't mind writing a few extra lines for it as it can be useful for me sometimes.
Think of it like using a soda opener for soda and using a nail cutter
I can do it with both but the soda opener Is easy to use in this case but , don't have much versatility like nail cutter.
And at the end of the day , I use state flow everytime because, I am lazy to learn live data for some projects as state flow can do what live data can even though live data will be much easier.
And you should decide what you want to choose and if you're not as lazy as me , I recommend go with both and use the one which is suitable each time.
Cheers.
Flow is the best practice
Livedata is used to observe data without having any hazel to handle lifecycle problems. Whereas Kotlin flow is used for continuous data integration and it also simplified the asynchronous programming.
Take Room Library as an example. First, it used livedata to transmit data from the database to UI. It solved most of the existing problems. But when there are any future changes in the database livedata is helpless in this situation.
After a while, the room used Kotlin flow to solve this problem. With Flow as return-type, room created a new possibility of seamless data integration across the app between database and UI without writing any extra code
read this article on medium website
In Android, LiveData and State are two classes that can be used to hold and observe data in your app. Both classes are part of the Android Architecture Components library, which is a set of libraries for building robust, testable, and maintainable apps.
LiveData is a data holder that is lifecycle-aware, meaning it only delivers updates to observers that are in an active state. It is useful for holding data that needs to be observed and updated in the UI, such as data from a network request or a database query.
State is a data holder that represents an immutable state value that can be observed. It is useful for holding data that does not change often, or data that should not be modified directly.
Which of these classes is "best" to use depends on your specific needs and requirements. Here are a few factors to consider when deciding between LiveData and State:
Mutability: LiveData is mutable, meaning its value can be changed, while State is immutable, meaning its value cannot be changed directly.
Lifecycle awareness: LiveData is lifecycle-aware, while State is not.
Transformation: LiveData supports transformation through the use of the Transformations class, while State does not.
In general, if you need to hold and observe data that needs to be updated in the UI and you want the data to be lifecycle-aware, LiveData is a good choice. If you need to hold and observe data that is immutable or does not change often, State is a good choice.
It is also worth considering whether you need to transform or map the data being held and observed. If you do, LiveData is a better choice because it supports transformation through the Transformations class.

Discuss using Kotlin Coroutines with MVVM?

I am using Kotlin Corountines with MVVM pattern and faced a problem: The data processing part is being done inside the ViewModel. While the repository seems not really necessary. When the application needs to call many APIs, the ViewModel will swell. What is everyone's solution to this problem? Thank you
The repository is needed, because in the case when you have a large app and gave too much responsibility to the ViewModel it's broke the separation of concerns principle.
Basically in the Andorids Guide to app architecture :
A first idea for implementing the ViewModel might involve directly
calling the Webservice to fetch the data and assign this data to our
LiveData object. This design works, but by using it, our app becomes
more and more difficult to maintain as it grows. It gives too much
responsibility to the UserProfileViewModel class, which violates the
separation of concerns principle. Additionally, the scope of a
ViewModel is tied to an Activity or Fragment lifecycle, which means
that the data from the Webservice is lost when the associated UI
object's lifecycle ends. This behavior creates an undesirable user
experience.
Instead, our ViewModel delegates the data-fetching process to a new
module, a repository.
And direct answer for your question:
Even though the repository module looks unnecessary, it serves an
important purpose: it abstracts the data sources from the rest of the
app. Now, our UserProfileViewModel doesn't know how the data is
fetched, so we can provide the view model with data obtained from
several different data-fetching implementations.
Basically, you can give all work to your ViewModel, but it's not recommended.
If you work/planning to work as a dev, maintaining your code, make it flexible to change and understandable for others is also important and usually, everyone appreciates this

Android MVVM design - should i split my viewmodel class in two?

I have an app with 2 distinctly seperate modes, (setup and run timers).
The app allows multi factor inputs from a user on one fragment and once the user wants the timer started, the app switches to a running fragment to show information about their running timer and it's setup.
I've designed an MVVM architecture for this, with my own class that extends ViewModel, my shared viewmodel has two distinctly different types of logic, setup logic (to check, parse and revise inappropriate user inputs), and running timer logic (to manage all the logic, data and state for a running timer from a user's inputs).
My shared viewmodel class is not small as the process of checking all permutations of user input is complex.  I'm wondering is it a bad idea to put all this logic into one viewmodel class? The setup portion is designed to be simple and all setup state is saved (so 10-20 seconds for the user to setup a timer seems appropriate), whereas the timer is designed to be allowed to run for hours, largely with the screen off.
 
Should I split the viewmodel logic into two different viewmodel classes to make a running timer more memory efficient?
I see a clear seperation of concerns and once I have my Room database designed and programmed, only the running timer will save data to the database. I want to keep the fragment classes as lightweight as possible.  If this is a sensible design choice, ill need to be careful with memory leaks between the two states, otherwise im defeating the purpose.
Edited to differentiate between the ViewModel object and a Shared viewmodel idea
As a_local_nobody says, it's up to you to decide how to design your app and distribute the responsibilities.
In case you are looking for our opinion about your philosophical doubts, I have to say that although the concept of the Shared ViewModels is very widespread, I am not a big fan.
In my projects, the most common and logical thing is that each ViewModel manages the logic of a single view. I always treat Shared ViewModels as an exception to the rule, since abusing them usually leads to a very tightly coupled code, very difficult to test and with unexpected side effects.

Using Kotlin Coroutines to replace LocalBroadcastManager for Firebase messaging

When using Firebase Cloud Messaging on Android, it is often desirable to notify the current Activity of an incoming push notification. One of the recommended ways to do this has been to use LocalBroadcastManager to send an Intent from the FirebaseMessagingService implementation to the Activity (StackOverflow example answer).
However, as of version 1.1.0-alpha01 (2018-12-17), LocalBroadcastManager is deprecated:
LocalBroadcastManager is an application-wide event bus and embraces layer violations in your app: any component may listen events from any other. You can replace usage of LocalBroadcastManager with other implementation of observable pattern, depending on your usecase suitable options may be LiveData or reactive streams.
While it is highly likely that this class will remain available for a while longer, I would like to start cleaning up our applications anyway, so I want to migrate to something better before Google actually removes the old way.
Right now, there are two main roles that these local broadcasts have in our apps:
Update the UI with the new data from the push notification. The way this worked was that each Activity that cares about the incoming push data has a broadcast receiver that listens for the appropriate message and updates its own view data.
Force the user to log out if the server sends a notification to end the session. This works with each activity having an instance of a broadcast receiver that listens for a logout event, ends the Activity, and starts the Login Activity.
As I see it, these use-cases have issues with both of their suggested alternatives:
LiveData is easiest to use in an Activity or Fragment as part of a ViewModel. However, ViewModel is only meant to be used from those classes that directly deal with the UI. Accessing the ViewModel from within the FirebaseMessagingService takes an ugly hack and is a really bad idea from an architectural perspective. Also, different activities and fragments have different ViewModel objects, and I don't want the service to need to access them all.
I can create a Kotlin object (a.k.a. Singleton) with a bunch of LiveData properties, have the FirebaseMessagingService update those LiveData objects from the incoming messages, and have the Activity observe those changes and copy them into its own ViewModel's LiveData properties. The problem with that is twofold: first, it requires me to have two identical LiveData objects for each piece of data, one in the ViewModel and one in the object; and second, it doesn't help me with handling the "log out event", because LiveData is meant to handle changing data, not listening to a stream of events. (I may be able to handle the second issue using this LiveData Event Wrapper, but that still feels like a bad hack over something that isn't meant to work this way.)
While reactive streams, such as RxJava, will probably do what I need, I already forced my team to learn Kotlin, Android Databinding, Android ViewModel, and a bunch of other new stuff in the last few months, and I don't think they can take much more. RxJava is also a large thing to add for just this one use, and we have no plans to rewrite the entire application to take advantage of it in order to justify its addition.
One suggestion I found was to use Kotlin Coroutines with Channels or Flows. These can be used very similar to reactive streams, but (unlike RxJava) are intended to be used with Kotlin and benefit from Kotlin's improvements over Java. This option is especially attractive now that Google has announced that they are focusing on Kotlin for Android development instead of Java.
While this seems to me to be the best option, I have not managed to find any feedback from others about whether it works and if there are side-effects and/or pitfalls to such an implementation. The only thing I found was an open issue on the kotlinx.coroutines repository about the need for providing an example of an application like this. While I'd love to contribute such an example, I don't think I know enough about it to create a good example, and I don't want my production apps to be the guinea pig. I also don't know whether it is better (or proper) to use explicit couroutines with Channel or to use suspend with Flow for this case.
In summary:
Are Kotlin Coroutines and their associated concurrency structures a good way to handle communication between Android Service and Activity?
If yes, which Kotlin type makes more sense to use, Channel or Flow?
Coroutines don't really help with the handoff of data from one software component to another. They help with the processing multiple units of asynchronous work using syntax that appears as if they were synchronous. That's the bottom line for coroutines. They're analogous to async/await syntax in JavaScript. While you might use a coroutine to access data from asynchronous sources, it doesn't give you any primitves to proxy that data on to other components.
LiveData probably works just fine for what you're trying to do. Don't conflate ViewModel with LiveData - they solve different problems. While you're correct that ViewModel should only be accessed by code that deals with UI, that guideline doesn't extend to LiveData. It's perfectly reasonable to expose a LiveData that reflects current data from FirebaseMessagingService that is later picked up by a ViewModel, transformed, and passed on to a view. This LiveData could be a singleton, or obtained via whatever dependency injection infrastructure you choose.
Bear in mind that LiveData is really only supposed to be used for managing changes in state. It's not a "stream" of data that your app can listen to. You will need to make sure that your infrastructure is state-based in order for this to work out well. FCM itself is not state-based, but if you want your views to respond to messages from FCM, you'll need to retain enough context between each message to make sure your UI responds consistently to new messages (or the lack of messages altogether).

Clean architecture. What are the jobs of presenter?

I have been reading some articles about the clean architecture, and how it can be implemented in android. I saw the sample app which shows its Android Implementation. Also, I went through a nice talk on Clean architecture on Android
So, I kind of understand most of the concepts, but there is some clarity that I would like to get on certain things.
As per my Understanding,
The View layer is the outer layer which deals with the UI, and
framework related stuff
The presenter is the direct communicator for the view, which accepts user inputs, and executes certain use cases based on this by passing it to the use case layer or the interactor layer.
Interactor executes the use-case, give it back to the callback sent by presenter,
Presenter again converts this result into a view understandable data structure (a ViewModel) and just pass it back to the view.
I am not listing more details about the inner layers like repository since my question is related to the above-mentioned steps
Here, does the presenter have the only job of acting as a mediator between UseCases and UI, as a data dispatcher?
Does it only do the view model to use case model conversion and vice-versa?
The input validation logics rely on which layer? Can it be inside the presenter? For example, if we take a small use case of a sign-up process,
Once the user entered the details and clicked sign-up button, and data sent to the presenter, is it like
Presenter validates the input values if any error is there notify
the view
If values are proper, convert it to a use case model, and execute
certain use case, and once the result is given by the interactor,
again convert to view model, send it to view.
And the second question is, who controls the navigation? The View or the Presenter or the UseCase?
who decides where to go next?
For example - Consider a use case of a login process, Where user will enter the credentials and click OK.
On successful login,
If users e-mail is not verified, go to email verify screen
If users profile is not completed, set-up the profile then only go to home screen
If user is new, show new offers screen, else directly go to home screen
So, who is responsible for making these decisions on which screen to go next? Is it the presenter, which decides and navigate the view accordingly? Or is it the use case handlers responsibility to inform the presenter what is the next State?
Sorry for making the question too long, but I just wanted to elaborate my current understandings. Thanks in advance
Here, does the presenter have the only job of acting as a mediator
between UseCases and UI, as a data dispatcher?
Yes
The input validation logics rely on which layer? Can it be inside the
presenter?
validation should rely on business layer not the presentation, can it be inside the presenter? sure it could, but what if you have multiple screens that take similar inputs, do you have to repeat your validation logic inside each presenter! you can argue that you can make a base presenter, but it's not the perfect solution, because presenter should have one purpose.
And the second question is, who controls the navigation? The View or
the Presenter or the UseCase?
do you consider the navigation is part of the Domain or the presentation or the data layer, it's likely related to the presentation layer, but you could make a small component inside the presentation layer which is control the whole navigation generically, So you can use this component the moment you decide that you do need other platform and throw your activities away. you can find this approach in the sample you've mentioned.
EDIT:0
How you pass data between modules where they have different models?
you simply use mappers, and the reason is to make each module has its own models or entities, so it would be easy to test each module separately.
About presenter and view, let's say you want show error message, presenter decides why it would be shown, view decides how it would be shown.
I think the problem in understanding the clean code presentation layer with Android, that Activities and fragments aren't only view, they're also The process and the lifecycle which your code would be live in, clean code came along to separate spaghetti code on those Activities and fragments.
EDIT:1
adding to the last point, it's clear now that Google and the support team there made a great effort to make Activities and Fragments dummy views as possible via introducing the great set of libraries "Architecture components". I encourage anyone to check them out, even if you're using MVP, you'll find a great benefits.

Categories

Resources