android – Is it correct to bind a ViewModel to a Service?-ThrowExceptions

Exception or error:

I’ve started using Architecture Components in my application and I’m still learning how to use it.

In my app I have an Activity showing different Fragments sequentially. In some of them I need to communicate with a background service in order to receive data from external BLE sensors. Since I need to interact with the service in more than one Fragment, I’m wondering if ViewModel is the right place where to make the binding. I’ve looked around but I didn’t found an answer.

Are there any problems binding a service inside a ViewModel?

How to solve:

It is not advisable to use Android framework classes inside ViewModels.

Here is the link on Google Developers blog post with the detailed explanation: ViewModels and LiveData: Patterns + AntiPatterns

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

Don’t let ViewModels (and Presenters) know about Android framework

Leave a Reply

Your email address will not be published. Required fields are marked *