Skip to content
Advertisement

Android application with MVVM architecture, writing to local Room database from a Service using MVVM, how should the Service write to the database?

In MVVM we have Activities and Fragments. Fragments and Activities have access to ViewModel. ViewModles have access to Repository. Repository has access to local and online database.

I want to build a Service component so that when the application is put on background the Service should continue to write to the local database.

This is how my application looks like:

https://source.coderefinery.org/Karagoez/mytourassistent

I couldn’t find reliable information on how Service are implemented in MVVM architecture.

Should the Service get the viewModel of the Activity it’s called from and call repository from that?

Should the Service be defined inside repository?

How should the Service component be implemented in the MVVM architecture when the Service is writing to database?

A similar question is asked there: What is the right place to start a service in MVVM architecture Android

But it get two answers that are quite different from each other.

Advertisement

Answer

I found the answer to my own question:

Make a static method in repository like this:

public static Repository getInstance(Context applicationContext) {
    if (repository == null) {
        repository = new Repository(applicationContext);
    }
    return repository;
}

Then use this method inside Service class like this:

repository = Repository.getInstance(getApplication());

Now you have repository inside Service which has access to database.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement