How to inject a ViewModel to another Viewmodel using Hilt

Viewed 1123

I have a word quiz app where there are different word games (multiple choice, spelling, match the words, etc). I have created a ParentViewModel to keep the common things, such as getting words from Room database, current question variable, etc. But, on the other hand, as each game has different aspects. They have their own viewmodels. I want to be able to use functions and variables from ParentViewModel in child view models. My question is if I am correctly injecting the ParentViewModel below or if there is another way to do this?

ParentViewModel:

@HiltViewModel
class ParentViewModel @Inject constructor(
    private val wordRepository: WordRepository
): ViewModel(){
    // Common things such as getting words from database.
}

Child view model (Different view model for each type of game):

@HiltViewModel
class SpellingViewModel @Inject constructor(
    practiceViewModel: PracticeViewModel
): ViewModel(){
    // Functions and varibles spesific to the current game.
}

Appmodule:

@Provides
@Singleton
fun provideParentViewModel(wordRepository: WordRepository): ParentViewModel {
    return ParentViewModel(wordRepository)
}
1 Answers

I think a baseViewModel should be created and inherit child classes from the parent class, You can create open functions that are in the parent class and use them in the child classes. Let me give you an example :

abstract class BaseViewModel : ViewModel(){open fun wordGameOne(){
        // do something
    }

    open fun wordGameTwo(){
        // do something
    }  
}

And in the child class, you can override

@HiltViewModel class GameOneViewModel @Inject constructor(
private val wordRepository: WordRepository) : BaseViewModel() {

    override fun wordGameOne(){
        // do something
    }
}
Related