Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it correct to bind a ViewModel to a Service?

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?

like image 736
hara Avatar asked Jan 10 '18 14:01

hara


People also ask

Can we use ViewModel in service?

It is not recommended using a ViewModel in a service. You could call your repository from your service itself. The ViewModel should be used closely with an Activity or a Fragment, so it's destined to live in the UI layer of your application. Therefore, I don't recommend using the ViewModel in a Service.

Can a ViewModel be shared between activity and fragment?

In android, we can use ViewModel to share data between various fragments or activities by sharing the same ViewModel among all the fragments and they can access everything defined in the ViewModel. This is one way to have communication between fragments or activities.

Can we use same ViewModel for different activities?

But you can achieve this by passing a single instance of a custom ViewModel factory which acts as a singleton factory, so it will always pass the same instance of your ViewModel among different activities.


1 Answers

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 presenters.

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

like image 62
Igor Bubelov Avatar answered Sep 19 '22 19:09

Igor Bubelov