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
Related
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.
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.
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).
I'm very new to MVP and can't seem to grasp this concept.
Basically I have an activity which has an onClick which displays a DialogFragment. The activity does what it needs to do with MVP. The DialogFragment does too. However they are fully independent with regards to linking to each other which is posing a problem for me. When the DialogFragment chain is finished doing what it needs to do, the presenter on this layer holds the data to update the view on the Activity layer. I want the presenter in the DialogFragment layer to give the data to the presenter in the Activity layer who can easily let their view know as it's already linked up nicely.
I've thought of interfaces, read about eventBus (I know nothing about this so be kind).
There must be a specific way of achieving this because it must be a common task, I know I'm going to be doing it a few times in this application.
Your model is the data source in MVP.
Don't know if I got your case properly or not but the model is responsible for providing data to the presenters.
So generally, your other presenter should be accessing the data it needs from the model. Your first presenter can ask the model to do insertions or updations etc required as per the business logic.
Once the alterations have been done by the model, your second presenter can access the data by asking for it from the model.
Hope, I made that out clearly.
As per clean architecture, design Interactor is part which contains all business logic. The term Interactor is quite confusing to me. Interactor seems to me like interacting between two different layers like data and presenter.
Is it the right term to use?
Can anyone please clear the purpose of Interactor? Which pattern does it follow?
If Interactor is not what it seems to me then what is the design pattern for
layer-layer interaction?
An Interactor is a design pattern that has nothing to do with "business logic" concept. Without going in deeper level of detail the Interactor pattern is an extension of the Command pattern; Each "business logic" object is treated as a "black box", a simple instruction to be executed for the client, decoupling the object that invokes the operation from the one that knows how to perform it. (refer to the bibliography for extended explanation).
In the android enviroment there is a simple 'rule' that demands to the programmer to do long time consuming task in a background thread, so the interactor patterns extends the "Command pattern" adding a layer of threading. All this complex stuff is implemented to create a "clean architecture" which entails a code that is scalable, maintainable and (arguably) understandable.
About the question .. ¿what is the design pattern for layer-layer interaction? It could have more than one rigth answer, depends of the situation. You could use a simple Interface as the entry point, so you could use the Adapter pattern, or maybe the Facade pattern, or if you want to do something more advanced you could implement an eventbus system.
Source:
Design patterns explained simply - auth Alexander Shvets. page 14 (Adapter), page 32 (Command), page 47 (Facade)
In the clean architecture approach, the Use Case Interactor is a layer that express the specific business rules. The Use Case Interactor interacts with the Entities (agnostic business rules) to achieve the Use Case intention. Entities can be used in another applications, once they are agnostics, on the other hand, the Use Case Interactors are specific application objects.
Can be found in the Clean Architecture book by Robert C. Martin at chapter 20
If you're familiar with domain driven design, then an Interactor can be compared to an Application Service. Also, it is incorrect to say "As per clean architecture, design Interactor is part which contains all business logic." On the contrary, Entities would contain the business (application-agnostic) logic; whereas Interactors would contain the application-specific logic. The Interactors would call the Entities to fulfill a use case, where a use case might be something like Create Purchase Order.
Going back to using Clean Architecture terms that Robert Martin (Uncle Bob) uses in his training video Architecture, Use Cases, and High Level Design, Uncle Bob says the following:
Interactors are application-specific. That means that any application specific business rule belongs inside an interactor. The interactors achieve their goals with application-specific logic that calls the application-agnostic logic within the entities. For example, the CreateOrderInteractor invokes both the constructor and the GetId method of the OrderEntity. Clearly, these two methods are application-agnostic. It's the interactor that knows how to call those two methods to achieve the goal of the use case.
For your observation that the Interactor seems like it is interacting between two different layers like data and presenter, that job actually belongs to the Boundary. The Boundary sits between the delivery mechanism and the Interactor, where the delivery mechanism might be a desktop application, MVC app, API, etc. This keeps the actual application and business code separate and transferable from one delivery mechanism to another.
He also has a nice diagram in the Extras section showing the interaction if you purchase the video. It looks something like the following:
Delivery Mechanism ==> Boundary ==> Interactor ==> Entity
P.S. The video referenced above is highly entertaining and informational.
From what I'm reading, it's the equivalent of the Presenter in the Model View Presenter (MVP) architecture.
It does business logic, not store or display data. It create a separate layer independent of how or where data is stored or displayed. It only cares about inputs and outputs in any format. It could be used in a combination of the Observer, Adapter, and Façade patterns to be an interface for callbacks, a generic extension point of the code, and a decoupled entry point for any non UI or data-storage usage, respectively.
I assume it is called an Interactor because the View interacts with it to calculate values and refresh any displayed UI elements and it interacts with the Model objects to extract data. It could also interact with a database for CRUD operations, but I think that's mostly addressed in the Repository Pattern as that isn't really business logic.
Interactors provides implementations for various use cases. Ideally, there should be one interactor per use case but it may differ according to the scale of your application.
Now, why it doesn't make sense for every application? Imagine you have two applications. In the first app, you just need to read a user. In the other application, you just update the very same user. You would have two different interactors like GetUserInteractor and UpdateUserInteractor. If you think about it, UpdateUserInteractor would make no sense for the first application (and vice versa), right? But your business/domain logic for both applications can still be the same where the implementations of both services (read and update) are included, for example, in the regarding business/domain object (or as separate use-case objects). These objects obviously encapsulate application agnostic business rules as they can be plugged under two or more different applications.
The communication takes place between the app and users is often application-specific. As others already mentioned, you can have your interactors execute commands on user actions. Or you can go for another similar way. But the command pattern is really convenient and arguably make the whole code more consistent, uniform, and easy to understand.
Last but not least, the other important aspect of interactors are 'boundary interfaces' which are the classes that polymorphically deployed for both input and output delivery.
(PS: For example, in Android, with the new architecture components, Fragment/Activity can be thought as an implementation of the input boundary as you deliver input events down to your business logic (or domain model) - it's the controller. LiveData is more like the output boundary implementation as it uses observer pattern under the hood and deliver the data back to the UI through the interactor. In this case, I think this makes the ViewModel a strong candidate for being the interactor since it receives the input events (and commands corresponding those events) and also contains the LiveData instance to be observed. Are all these decoupled nice, or, polymorphically deployed? Well, this is mostly related to your design. And with coroutines, now it seems like there's no need for callbacks/listeners - so another dimension into this picture.)
This is my take. I hope it's clear.
It's MVP pattern. Yes as you said it's mediator between presenter and data(as a form of rest call or shared preference or Sqlite).