I have abstract class BaseViewmodel(uiActions: UiActions) : ViewModel(), UiActions by uiActions
All ViewModels in project extends BaseViewModel
For example, 2 of my ViewModels (without bodies):
class SearchViewModel(uiActions: UiActions) : BaseViewModel(uiActions)
class HistoryViewModel(uiActions: UiActions) : BaseViewModel(uiActions)
All viewModels does NOT have any arguments except uiActions: UiActions
So, factories are almost similar, difference is in class name only. For example:
class SearchViewModelFactory(private val uiActions: UiActions) : ViewModelProvider.Factory {
@Suppress("UNCHECKED_CAST")
override fun <T : ViewModel?> create(modelClass: Class<T>): T =
SearchViewModel(uiActions = uiActions) as T
}
class HistoryViewModelFactory(private val uiActions: UiActions) : ViewModelProvider.Factory {
@Suppress("UNCHECKED_CAST")
override fun <T : ViewModel?> create(modelClass: Class<T>): T =
HistoryViewModel(uiActions = uiActions) as T
}
Can I create 1 factory and use it everywhere?
You can write a factory that can be used for multiple different ViewModel types. That why the create
function has a Class
parameter:
class UiActionsViewModelFactory(private val uiActions: UiActions) : ViewModelProvider.Factory {
@Suppress("UNCHECKED_CAST")
override fun <T : ViewModel?> create(modelClass: Class<T>): T = when (modelClass) {
SearchViewModel::class.java -> SearchViewModel(uiActions)
HistoryViewModel::class.java -> HistoryViewModel(uiActions)
}
}
I'm not sure about what UiActions
is, but be careful to avoid leaking any view/activity/fragment references to the ViewModel.