BoundService + LiveData + ViewModel best practice in new Android recommended architecture

android mvvm architecture components
android mvvm livedata
android app architecture diagram
advantages of viewmodel android
android kotlin viewmodel
shared viewmodel android
android viewmodel dependency
android viewmodel livedata

I been struggling a lot thinking about where to place Android Services in the new Android recommended Architecture. I came up with many possible solutions, but I cannot make up my mind about which one is the best approach.

I did a lot of research, and I couldn't find any useful guideline nor tutorial. The only hint I found about where to place the Service in my app architecture is this one, from @JoseAlcerreca Medium post

Ideally, ViewModels shouldn’t know anything about Android. This improves testability, leak safety and modularity. A general rule of thumb is to make sure there are no android.* imports in your ViewModels (with exceptions like android.arch.*). The same applies to presenters.

According to that, I should place my Android Services on the top of my Architecture Components hierarchy, at the same level as my Activities and Fragments. That's because Android Services are part of the Android framework, so ViewModels shouldn't know about them.

Now, I will explain briefly my scenario, but only to make the panorama clearer, not because I want an answer for this specific scenario.

  • I have an Android Application that has a MainActivity with many fragments in it, all of them tied together in a BottomNavBar.
  • I have a BluetoothService bound to myActivity and one of its fragments (because I want the Service to have the same lifecycle as the Activty but I also want to interact with it directly from my fragment).
  • The fragment interacts with the BluetoothService to get two types of information:
    • Information about the state of the Bluetooth connection. Doesn't need to be persisted.
    • Data that comes from the Bluetooth Device (it is a Scale, so weight and body composition in this case). Needs to be persisted.

Here are the 3 different architectures I can think of:

LiveData inside AndroidService

  • The LiveData with the state of the connection and with the weight measurements coming from the Bluetooth Device are inside the BluetoothService.
  • The Fragment can trigger operations in the BluetoothService (scanDevices for example)
  • The Fragment observes the LiveData about the state of the connection and adapts the UI accordingly (for example, enable a button if the state is connected).
  • The Fragment observes the LiveData of the new weight measurements. If a new weight measurement comes from the BluetoothDevice, the Fragment then tells its own ViewModel to save the new data. It is done via a Repository class.

Shared ViewModel between fragment and AndroidService

  • The Fragment can trigger operations in the BluetoothService (scanDevices for example)
  • The BluetoothService updates the Bluetooth related LiveData in the shared ViewModel.
  • The Fragment observes the LiveData in its own ViewModel.

Service ViewModel

  • The Fragment can trigger operations in the BluetoothService (scanDevices for example)
  • The BluetoothService updates the Bluetooth related LiveData in its own ViewModel.
  • The Fragment observes the LiveData in its own ViewModel and the BluetoothService ViewModel.

I am pretty sure I should place them on top of the architecture and treat them just like an Activity/Fragment, because BoundServices are part of the Android Framework, they are managed by the Android OS and they are bound to other Activities and Fragments. In that case, I don't know what's the best way to interact with LiveData, ViewModels and Activities/Fragments.

Some might think that they should be considered as a DataSource (since in my case it's getting data from a scale using Bluetooth), but I don't think this is a good idea, because of all what I've said in the previous paragraph and specially because of what it says here:

Avoid designating your app's entry points—such as activities, services, and broadcast receivers—as sources of data. Instead, they should only coordinate with other components to retrieve the subset of data that is relevant to that entry point. Each app component is rather short-lived, depending on the user's interaction with their device and the overall current health of the system.

So, finally, my question is:

Where should we place our Android (Bound) Services and what is their relation with the other architectural components? Is any of these alternatives a good approach?


In my opinion, Service should be on same level as Activity/Fragment, because it's Framework component & not MVVM. but because of that Service doesn't implements LifecycleOwner and it's Android Framework Component, it shouldn't be treated as data source because it can be entry point to application.

So, dilemma here is that sometimes (In your case), Service acts as data source which provides data from some long running task to UI.

So what it should be in Android Architecture Component? I think you can treat it as LifecycleObserver. because, no matter what you do in background, you'll need to consider about lifecycle of the LifecycleOwner.

Why? because, we usually do bind it to LifecycleOwner (Activity/Fragments) & to do long running tasks off the UI. So, it can be treated like LifecycleObserver. In such a way we made our Service as "Lifecycle aware component" !


How you can implement it?

  1. Take your service class and implement LifecycleObserver interface to it.

  2. When you bind your service to Activity/Fragment, during your service connection of your service class, add your service to your activity as LifecycleObserver by calling method getLifecycle().addObserver(service class obj)

  3. Now, Take an interface in service class to provide callback from service to your UI and every time your data changes, check that if your service has at least on Lifecycle event create or resume to provide callback with.

In such a way, we won't require LiveData to update to from service and even no ViewModel (Why do we need it for service? We don't need configuration changes to survive on service lifecycle. And main task to VM is that to consist data between lifecycles).

Hope i made it clear for you !

Guide to app architecture, This guide encompasses best practices and recommended architecture for building robust, production-quality apps. This page assumes a  The Repository is not part of the Architecture Components libraries, but is a suggested best practice for code separation and architecture. A Repository class handles data operations. It provides a clean API to the rest of the app for app data. A Repository manages query threads and allows you to use multiple backends.


One way to avoid direct contact with an Android service while still being able to use it is through an interface object. This is part of the "I" for Interface Segregation in the acronym, SOLID. Here is a small example:

public interface MyFriendlyInterface {
    public boolean cleanMethodToAchieveBusinessFunctionality();
    public boolean anotherCleanMethod();
}

public class MyInterfaceObject implements MyFriendlyInterface {
    public boolean cleanMethodToAchieveBusinessFunctionality() {
        BluetoothObject obj = android.Bluetooth.nastySubroutine();
        android.Bluetooth.nastySubroutineTwo(obj);
    }

    public boolean anotherCleanMethod() {
        android.Bluetooth.anotherMethodYourPresentersAndViewModelsShouldntSee();
    }
}

public class MyViewModel {
    private MyFriendlyInterface _myInterfaceObject;

    public MyViewModel() {
        _myInterfaceObject = new MyInterfaceObject();
        _myInterfaceObject.cleanMethodToAchieveBusinessFunctionality();
    }
}

Given the above paradigm, you are free to place your services in a package that's outside your packages that contain POJO code. There is no "right" location to put your services -- but there are definitely WRONG places to put them (e.g. where your POJO code goes).

[Question] Using ViewModels in Service · Issue #137 · android , But I want to know what's the best practice to use ViewModel in Service . +1 10. It’s flagship offerings, ViewModel and LiveData, can be used in almost any app. Plus, now that Google is now pushing MVVM architecture, these libraries are a perfect fit. Let’s see how we can get started with ViewModel and LiveData! See the YouTube video tutorial for this article to learn about Android Architecture Components in video form


In my opinion using LiveData in servise is comfortable

    class OneBreathModeTimerService : Service() {
        var longestHoldTime = MutableLiveData<Int>().apply { value = 0 }
        ...
    }

Then in fragment

     override fun onCreate(savedInstanceState: Bundle?) {
         mServiceConnection = object : ServiceConnection {

            override fun onServiceConnected(name: ComponentName, binder: IBinder) {
                mOneBreathModeService = (binder as OneBreathModeTimerService.MyBinder).service

                mOneBreathModeService!!.longestHoldTime.observe(this@OneBreathModeFragment, androidx.lifecycle.Observer {
                    binding.tvBestTime.text = "Best $it"
                })
            }

            override fun onServiceDisconnected(name: ComponentName) {}
     }

I am not pro in LiveData, but what can be wrong with such approach?

ViewModels and LiveData: Patterns + AntiPatterns, A collection of patterns and recommendations that we've been collecting since we released the first Typical interaction of entities in an app built with Architecture Components. Ideally, ViewModels shouldn't know anything about Android. LiveData<String> snackbarMessage = new MutableLiveData<>();. In most cases, onCreate() is a good place to start observing a ViewModel’s LiveDatas. Here’s a noteworthy excerpt from the official Android documentation on LiveData :


How about treating your service like this?

Teamviewer quicksupport 145224 apk, The recommended way to communicate between fragments is to create a shared MVVM architecture, ViewModel and LiveData (Part 1 · Android Practices: ICS It's the best of Android, built with new and reimagined apps, so even the most is scoped to the activity.5 The The Pick: MVVM-C. A bound service is the server  During Google I/O, Google introduced architecture components which includes LiveData and ViewModel which facilitates developing Android app using MVVM pattern.. In the first article of this series, we discussed how can these components serve an android app that follows MVVM.


Android fundamentals 10.1 Part A: Room, LiveData, and ViewModel, The diagram below shows a basic form of the recommended architecture for Room database: Database layer on top of an SQLite database that takes care of​  In my main Android app I put LiveData fields in a ViewModel. This ViewModel can then be accessed/bound from both my Activity and my Fragments. To do this I use the method ViewModelProviders.of which expects either android.support.v4.app.Fragment or android.support.v4.app.FragmentActivity .


User Jeel Vankhede, movies.stackexchange.com. Top Answers. 14 · BoundService + LiveData + ViewModel best practice in new Android recommended architecture · stackoverflow. If you want more info on state and status handling with Architecture Components using a "clean" architecture you may checkout Eiffel on GitHub. It's a library I created specifically for handling immutable view states and data binding with ViewModel and LiveData as well as glueing it together with Android system operations and business use cases


android-architecture - St4k, Marian Paździoch. 6,851. 42. votes. 4. answers. 5,609. views. BoundService + LiveData + ViewModel best practice in new Android recommended architecture. This guide encompasses best practices and recommended architecture for building robust, production-quality apps. This page assumes a basic familiarity with the Android Framework. If you are new to Android app development, check out our Developer guides to get started and learn more about the concepts mentioned in this guide.