Search code examples
androidviewmodelandroid-architecture-componentsandroid-viewmodelandroid-mvvm

Should 2 Activity's have separate ViewModels if the method usages don't overlap?


I have 1 Activity that only displays and deletes Notes from a RecyclerView. I have another Activity that only adds and updates new items.

At the moment they both use the same ViewModel class:

public class NoteViewModel extends AndroidViewModel {
    private NoteRepository repository;
    private LiveData<List<Note>> allNotes;

    public NoteViewModel(@NonNull Application application) {
        super(application);
        repository = new NoteRepository(application);
        allNotes = repository.getAllNotes();
    }

    public void insert(Note note) {
        repository.insert(note);
    }

    public void update(Note note) {
        repository.update(note);
    }

    public void delete(Note note) {
        repository.delete(note);
    }

    public void deleteAllNotes() {
        repository.deleteAllNotes();
    }

    public LiveData<List<Note>> getAllNotes() {
        return allNotes;
    }
}

Should I instead create 2 separate ViewModels, one for each Activity?


Solution

  • That depends on whether you are going for simpler maintainability or clearer separation of concerns.

    There it nothing wrong with having a single ViewModel for both activities, but consider that a ViewModel is supposed to model the view.
    Having some functions in the ViewModel that are not used by Activity A, and other functions not used by Activity B, does not really fit well with the idea that the ViewModel should be a model of the functionality of the View.

    My recommendation would be two separate ViewModel.