I am in the process to rewrite my app code from using Java to Kotlin with MVVM. My app uses the Sugar ORM instead of Room DB at the moment, however, I still would like to use some of the potentials of MVVM.
My goal is to instantiate the DAO and Repository in one place for instance in the application and create only one instance of it for the whole app the correct way.
DAO - Kotlin
class FirstDao {
...
}
class SecondDao {
...
}
Repository - Kotlin
class InternalRepository(private val firstDao: FirstDao,
private val secondDao: SecondDao
) {
...
}
View Model - Kotlin
class FirstViewModel(private val repository: InternalRepository) :
ViewModel() {
...
}
View Model Factory - Kotlin
class FirstViewModelFactory(
private val repository: InternalRepository
): ViewModelProvider.Factory{
override fun <T : ViewModel> create(modelClass: Class<T>): T {
if (modelClass.isAssignableFrom(FirstViewModel::class.java)) {
@Suppress("UNCHECKED_CAST")
return FirstViewModel(repository) as T
}
throw IllegalArgumentException("Unknown ViewModel class")
}
}
Activity - Java
FirstDao firstDao = new FirstDao();
SecondDao secondDao = new SecondDao();
InternalRepository repository = new InternalRepository(firstDao, secondDao);
FirstViewModelFactory factory = new FirstViewModelFactory(repository);
viewModel = new ViewModelProvider(this, factory).get(FirstViewModel.class);
Application - Java
public class MyApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
SugarContext.init(this);
...
}
...
}
The code itself works correctly, however, when I have more DAO I have to instantiate every single one in the activity including the repository and there is a risk that the DAO and repository will be instantiated multiple times.