Search code examples
androidmvvmandroid-asynctask

One ViewModel for multiple Views or multiple ViewModels for a single View?


I am working on an Android App that trains the ear of the player, by making them replay on guitar whatever they hear from the phone. I made the note (and chord) recognition part the following way: a main thread that displays the information and listens to the buttons, an AsyncTask that records the sound and sends the data to be analyzed and another AsyncTask that analyzes and determines what notes have been played.

The note recognition is real-time, so I placed the Analyzer AsyncTask in a ViewModel. The recognized notes and chords are kept in LiveData fields, so whenever they change, the main thread (which is represented by the View) is notified.

Right now I am working on a game using this recognition, but I intend to make a tuner, too. The game and the tuner will be using the same recognition algorithm.

My question is: How should I approach this? The game and the tuner will be having their own functionalities, too. Should I keep the Analyzer ViewModel separate from the individual game and tuner ViewModels? That would mean that I would use two ViewModels for each of those two Views. I figure I shouldn't repeat the Analyzer code in both of the individual ViewModels, and also I shouldn't write the functions for the game and for the tuner in the same ViewModel, because there will be useless code (the game will never use individual tuner functions).


Solution

  • You should probably have your common recognition algorithm in your Model actually (or even in some service layer independant from the Model), not in your ViewModel. The ViewModel is made to be bound to the View, not to perform business logic like note recognition.

    In this case, the ViewModel would be in charge of sending the recordings to the Model, which saves them as LiveData objects. The ViewModel retrieves them and expose them to the View as LiveDataViewModel objects for example.