If you’re like me and nonetheless haven’t gotten used to the Dependency Injection framework (do not you assume it complicates issues?), you most likely have been implementing the ViewModelProvider.Manufacturing unit()
interface on your view fashions that has customized constructor parameters.
A number of ViewModel Manufacturing unit Courses
class AViewModelFactory(non-public val repository: ARepository) :
ViewModelProvider.Manufacturing unit {
override enjoyable <T : ViewModel> create(modelClass: Class<T>): T {
return AViewModel(repository) as T
}
}
For instance, AViewModelFactory
is the view mannequin manufacturing unit class that creates ViewModel
which takes in ARepository
as a constructor parameter. So what in case you have one other ViewModel to create? Then, you want to implement one other manufacturing unit class (i.e. BViewModelFactory
)
class BViewModelFactory(non-public val repository: BRepository) :
ViewModelProvider.Manufacturing unit {
override enjoyable <T : ViewModel> create(modelClass: Class<T>): T {
return BViewModel(repository) as T
}
}
Nicely, this appears redundant and may be simplified.
Kotlin Lambda and Object Expressions
You possibly can merely the implementation with out explicitly having these manufacturing unit lessons utilizing Kotlin Lambda Capabilities and Object Expressions as you may see within the following createViewModelFactory()
helper operate.
enjoyable <VM : ViewModel> createViewModelFactory(createViewModel: () -> VM)
: ViewModelProvider.Manufacturing unit {
return object : ViewModelProvider.Manufacturing unit {
override enjoyable <T : ViewModel> create(modelClass: Class<T>): T {
return createViewModel() as T
}
}
}
The createViewModel
is the lambda the place the callers outline how they need to create the ViewModel. The return of this operate is the implementation of ViewModelProvider.Manufacturing unit()
interface for the ViewModel that you just need to create.
So, as an alternative of making the ViewModel like this:
@Composable()
enjoyable WithoutHelperFunctions() {
val aViewModel: AViewModel = viewModel(
manufacturing unit = AViewModelFactory(ARepository()),
)
val bViewModel: AViewModel = viewModel(
manufacturing unit = BViewModelFactory(BRepository()),
)
}
You possibly can create the ViewModel with this createViewModelFactory()
helper operate:
@Composable()
enjoyable WithHelperFunctions() {
val aViewModel: AViewModel = viewModel(
manufacturing unit = createViewModelFactory {
AViewModel(ARepository())
}
)
val bViewModel: BViewModel = viewModel(
manufacturing unit = createViewModelFactory {
BViewModel(BRepository())
}
)
}
The profit is you not must declare a number of manufacturing unit lessons. You simply must have one createViewModelFactory()
helper operate.
Associated ViewModel Creation Articles
When you’re not aware of ViewModel creations, chances are you’ll need to go to my following weblog posts:
Supply Code
GitHub Repository: Demo_ViewModelFactory