You could use interfaces and hilt.
interface IMyViewModel {
fun getTextA() : String
}
@HiltViewModel
class MyViewModel() : ViewModel(), IMyViewModel {
fun getTextA() : String {
//do some cool stuff
}
}
class MyViewModelPreview() : IMyViewModel {
fun getTextA() : String {
//do some mock stuff
}
}
@Composable
fun MyScreen(myVm = hiltViewModel<MyViewModel>()) {
Text(text = myVm.getTextA())
}
@Preview()
@Composable
fun MyScreenPreview() {
MyScreen(myVm = MyViewModelPreview())
}
In this point MyViewModel is an implementation of IMyViewModel annotated with @HiltViewModel and hiltViewModel make all the required wired for you, In preview you could use any other simple mock implementation.
If you need to provide some dependency to your view model use injected constructor with dagger injection(already supported by hilt). Obviously this dependency should be paced on your actual viewmodel and your preview implementations need to be just a wrapper class with no other dependency since they function is just satisfy arguments
@HiltViewModel
class MyViewModel @Inject constructor(
private val myDependencyRepositoryOne: MyDependencyRepositoryOne,
private val myDependencyRepositoryTwo: MyDependencyRepositoryTwo)
: ViewModel(), IMyViewModel {
fun getTextA() : String {
//do some cool stuff
}
}
Here is another useful resource related to viewmodel injection in compose