I'm working on an Android app (in Java) and trying to use Google's recommended application architecture, but I can't seem to figure out where services fit in to this architecture. I've done a lot of looking online and there is no clear consensus on how this should be done.
For context, my application communicates with a BLE device. I've created BLEService which extends Service that establishes the connection with the device, and provides methods send data to the device. The device can also send data back (and thus needs to notify the app when data is received).
My question is, where should the ServiceConnection reside, and how should it be stopped/started? From my research, there are a couple options that each have their pros and cons.
The Service is started/stopped in the Activity, the Activity observes events from Service. The Activity forwards the events to the ViewModel for processing. This pattern keeps all of the Android components together, but gives more responsibility to the View than I believe it should. The View should only be responsible for handling the UI.
The Service is stopped/started in the ViewModel (perhaps by extending AndroidViewModel). The ViewModel observes events from the Service and processes the events. This pattern is nice because the ViewModel is handling the business logic, however if Service implements its events via LiveData, Google states that the ViewModel must not observe LiveData. Another option is for the Service to implement events via something like EventBus, but there are a lot of people against using EventBus because it is easy to abuse. I have also heard that ViewModel should not have any Android-specific code in it for testing purposes.
The Service exists in some sort of Repository/Model. The ViewModel forwards its sends and observes events from the Repository/Model. This solution is nice because interfacing with a Bluetooth device does seem like it fits the intended purpose of what a Model is. However, it suffers the same issue that the ViewModel must not observe LiveData. I have seen Transformations.switchMap suggested in this case, which causes a LiveData in the ViewModel to be updated in response to a change in a LiveData from the repository. I'm not totally clear on using this strategy, or how it would function in my specific use-case. There's also the issue that the repository needs access to Context, and I have heard it's bad practice to hold on to an instance of Context. Furthermore, I have also read that a Repository should not hold on to callbacks from the ViewModel.
I'm sure there's no perfect solution, but if someone could point me in a direction of best practices, particuarly in my use-case, that would be immensely helpful.
Related
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
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).
it's more a general question rather than a specific one.
Basically I'm developing an Android app which communicates with Ble Peripheral Device.
I handle Ble communication using RxAndroidBle library. As for the general pattern, I decided to try Mosby MVI, however
that's not that important.
What I did so far is I created BluetoothManager class which is responsible for performing all the operations
on the Ble Device. This class is a Singleton (I know it's not recommended on Android) and I scoped it using Dagger,
that this is injected only to those interactors that should perform some Ble communication.
This class returns Observables with some POJOs, which are transformed to ViewStates in interactor and than moved higher to the UI.
Subscriptions are in the presenters following Mosby MVI pattern.
Basically thanks to that I treat this Ble Device as a regular data source, same as some retrofit service or any db.
And that was totally fine as long as I was performing atomic operations like writing and reading some single characteristics.
The problem is when I need to fire up some kind of a synchronization that may take quite a lot of time, should be done on background,
should NOT be bound to UI, however on some screens user should be able to see the progress.
Here I started to think about using Android Service and putting all the Ble Communication logic there,
however in my opinion using Android service breaks any attempts of logic separation and I couldn't find a good way to fit it there.
Third option was having a service for synchronization and preserving BluetoothManager for atomic operations bounded to UI, however
I think it's messy and I would be nice to have all the Ble stuff in one place.
I know it's long but it all goes to one question -> what would be the best pattern to follow when communicating with Ble device on Android
to preserve layers separation and keeping it as independent as possible.
I could not find any good articles about handling that, if there are any they are quite out dated, not using Rx approach.
If it's too generic, I can specify some more details, but I'm looking more for an architectural advice rather than code snippets.
What about something like this:
instead of subscribing in presenter to bluetooth directly, introduce a class BleRepository
Then BleRepository provides a metod Observable<Foo> (Foo is whatever data your Presenter / UI should see) and operations to execute stuff like doA(). Something like this:
interface BleRepository {
// Read Data
Observable<Foo> getDataObservable();
// Write Data operations
Completable doA();
Completable doB();
}
So the Presenter subscribes to BleRepository instead to bluetooth connection directly.
So now whenever you do a "write operation" you just execute it but you always read new data from getDataObservable() even if the write operation itself returns new data, reading data always goes through getDataObservable().
So BleRepository is basically just a public API your presenter uses. The Presenter doesn't know about the actual Bluetooth connection. So what you can do next is moving the actual bluetooth connection into an android service, lets call it BluetoothService. Then BluetoothService get's connected and whenever the sync runs or whatever else your connection receives / sends, it emits that data back to BleRepository.getDataObservable() which is subscribed by the service. You just have to ensure that both Service and Presenter "share" the same BleRepository instance. i.e. use dagger to inject the same instance or make it a singleton ... whatever works best for you.
Depending on your usecase you can also make the BluetoothService subscription aware like start the android service in RxJavas onSubscribe and stop the service in on unsubscribe / onTerminal. But it sounds like your usecase is slightly different so that Bluetooth is still connected even if Presenter / view has been destoryed, right? Whatever, the idea is use Service (Services if it makes sense for your proble) but they all somehow push the data into BleRepository that then delivers the data to the Presenter.
I am developing an Android app that does Human Activity Recognition.
It basically works like that - Service constantly reads the accelerator data and stores the recognized activity (i.e. Walking, running) in a database. The user can see all of the recognized activities in an ListView in activity (accesses the database). Every User table in the database has a pa_goal (physical activity goal) field which the Service reads from the database and does some checks.
The user, of course, can change this goal from an activity. Since I will be implementing the MVP architectural pattern.
I am unsure where to put the Service? It surely isn't View. Any advice?
In a clean architecture, which is what I am assuming you are using MVP for, there is the idea of separating the framework from the business logic. This is essentially what a normal presenter allows you to do.
In this case its not a view you are dealing with but the principle is similar. You don't want all your business or application logic mixed in the Android code when you can separate them out for nicer, more single responsibility classes. So I would say that while it isn't a view you should still have a presenter type class (probably better to be called controller or manager maybe).
This class would be a POJO that controls how your service behaves which is easily testable with standard junit tests and service mocks. This class and the service could then be put into its own feature package and interact with the back end models the same way as your presenters.
So, in summary, the role is of another feature of your app that sites alongside the other features (which are usually just views in my experience).
Hope that helps
This article helped me in a similar situation, although may not be exactly yours, the idea is the same:
https://android.jlelse.eu/android-bound-services-and-mvp-12ca9f70c7c7
Basically, the author works around the fact that a bound service is tightly coupled to an activity, and it adds extra lifecycle calls to it.
I am in the same situation. Finally I decided to do something like this:
Activities or Fragments are out of scope, they do not know anything about MVP BUT i am going to use an event bus like Otto to send signals/events, So:
My classes which extends some kind of Presenter know nothing about Android Context but they will have an MvpView interface, with only onAttachPresenter and onDetachPresenter.
The class which extends Service will have a Presenter attribute and implements some MvpView interface with onSucess, onError, onStart, onComplete or something like that and same events for Otto (onSucessEvent, onErrorEvent, onStartEvent, onCompleteEvent).
So when I need to do something the Activity or Fragment will start the service, the service will "start" or talk with the Presenter and when the presenter finish with success will call to mvpView.onSuccess() and store the info inside a local DB with SQLite (storeIO maybe) and finally the Service will invoke Otto and pass the signal (without any data on it), probably onComplete.
Finally the signal will be catched by my UI (fragment maybe) and retrieve all the info inside a DB in SQLite.
So when the onSucess happens the UI will show the latest and best data BUT when onError happens will (at least) show some info (or not if you want) saying to the user "there was a problem but at least you can see something", bot onSuccess and onError will call onComplete after all.
Do not know if this is the best solution but in this case I think I am not going to deal with Activities or Fragments lifecycle and do not care about onSaveInstance and restore data when the user rotates the device. It will always fetch the latest data inside DB, and if something happens (no internet connection) you can at least show something when you receive the onComplete Signal.
Some facts I am still thinking:
The Presenter won't be a singleton class
Presenter knows nothing about Context but yes with MyApplication class
What happens if for one screen (Fragment) you have differents service with differents onSuccessEvents? Simply use some kind of action as an ID, to identify them.
Never make the Activity Fragment implements the MvpView, you will have to deal with the lifecycle.
Short stated my question is: in MVP architecture is it a good idea to use a Service as
Presenter to control a Model implemented as Service ?
Alternative question: Is using a Service to control another Service a good idea ?
The context:
I am writing an app that communicates with a bluetooth sensor.
The app has a Service
(aka BluetoothService) that makes the connection and manages the communication with the sensor.
The app has several Fragments but just few of them are related to the operations that
the Bluetooth sensor does. A user should be able to start an operation, navigates to different
fragments and later watches the results of the operation(s) done by the sensor.
My purpose:
I want to write a component (aka BluetoothController) that makes the links
between the sensor (represented in my app by BluetoothService) and the rest of
the app. The BluetoothController contains Objects that described what kind of
operation has to be done by the sensor (only one operation, serial operations,
type of the operation, ...), so BluetoothController 's purpose is to let
the operations be independant to Bluetooth sensor and then be able to test the app
with a mock bluetooth class. I see BluetoothService as a model and
BluetoothController as a presenter, am I wrong ?
Why a Service:
Because it does not die if the user navigates between fragments
Because it is accessible through the whole app via bindService
Because bindService is the only entry point, I guess I can control that just
one operation is done at a time
Because I see Service as an active component, so it can keep on receiving data even if there is nothing bound to it
This service would be both started and bind (like a music player):
to be able to keep on running even if no components are bound to it,
to ease communication
All services would be in the application process to let communication be done
without binder but rather
method call.
Any suggestion would be highly appreciate , thanks in advance
Why not something else:
RetainedFragment are (for me) just container
pojo presenter are just gateway between views and models, they should die if
they are not attached to a view.
Conclusion
Am I wrong? Do you see difficulties in this architecture? Are there other Android
components that suits my purpose better?
Any suggestions would be highly appreciated, thank you in advances