I try understanding ViewModel. I create ViewModel:
public class UsersViewModel extends ViewModel {
private final UsersRepository usersRepository;
public UsersViewModel(UsersRepository usersRepository) {
this.usersRepository = usersRepository;
}
public LiveData<List<User>> loadAll() {
return usersRepository.getAll();
}
}
But I not understand 2 things:
UsersRepository
to this VievModel
? When I used presenter I can create it with dagger 2 like this:@Module public class PresentersModule { @Singleton @Provides UsersPresenter provideUsersPresenter(UsersRepository usersRepository) { return new UsersPresenter(usersRepository); } }
but how can I do it with ViewModel
? Like this?
@Module
public class ViewModelsModule {
@Singleton
@Provides
UsersViewModel provideUsersViewModel(UsersRepository usersRepository) {
return new UsersViewModel(usersRepository);
}
}
How can I get this ViewModel in fragment? With presenter I can this:
presenter = MyApplication.get().getAppComponent().getUsersPresenter();
Dagger2 required you to create ViewModelModule
and do the binding to your ViewModels
I know you are asking about Dagger2, but if you are starting a new project, maybe you can check out Koin
which provides a lightweight injection.
I've used it in some of my production apps and it works fine with lesser lines of code.
You can just declare in your module like
viewModel { MyViewModel(get()) }
Then in your activities / fragments / classes (you need to extend KoinComponent
), just write
val myViewModel : MyViewModel by viewModel()
It will handle the creation itself.
For more information can refer
https://insert-koin.io/
https://start.insert-koin.io/#/getting-started/koin-for-android?id=android-viewmodel
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With