I am trying to understand how to correctly use the MVVM pattern in iOS. Lets assume we have a music player app with a playlist like in the following sketch:
I have a PlaylistViewController and a PlaylistViewModel. Furthermore the cells (SongTableViewCell) have a view model SongCellViewModel which holds the data (song name,..). If the user presses the X button on the TableViewCell I have to delete the song from the database. The cell is calling the following function in the SongCellViewModel:
func deleteSongFromPlaylist() {
DatabaseService.shared.deleteSong(self.song)
}
My question: Is it good to do it that way? It doesn't feel right to initiate database operations in the view model of the TableViewCell.
I suggest moving such operations to PlaylistViewModel
and do all operations from there. It also simplifies implementation of later improvements like showing activity indicator if needed or reloading certain cells or views from there.
I think that SongCellViewModel
should have a actionBlock
which will take enum
with associated values - for example .select(song)
.delete(song)
- and this way you can easily communicate between PlaylistViewModel
and SongCellViewModel
.
One more suggestion is to use Dependency Injections instead of using shared
for all type of services.