I am using Dagger 2 with Kotlin. I`ve provided a viewmodel(CarViewModel) injection on the following way. Everywhere is written that it has to be done via ViewModelFactory injection. I want to ask if my way to directly inject viewmodel is correct? Here is my AppModule:
@Module
class AppModule {
@Provides
@Singleton
fun getContext(application: Application): Context = application.applicationContext
@Provides
@Singleton
fun getDb(context: Context): MyDatabase = MyDatabase.getInstance(context)
@Provides
fun injectViewModel(application: Application): CarViewModel=
ViewModelProvider.AndroidViewModelFactory.getInstance(application).create(CarViewModel::class.java)
}
Than injected in activity:
@Inject
lateinit var carViewModel: CarViewModel
No, your way of injecting a view model is not quite correct. The main reason is that the view model isn't associated with an activity, so it won't be reused when the activity is recreated, instead it will be recreated as well. The proper way of creating a view model is using ViewModelProvider
, not the ViewModelProvider.Factory
directly:
// `this` refers to the activity or fragment
viewModel = ViewModelProviders.of(this)[MyViewModel::class.java]
or:
viewModel = ViewModelProvider(this)[MyViewModel::class.java]
if you use the newest alpha version (ViewModelProviders.of()
is deprecated).
If you want to inject a view model and also be able to inject into view model (using constructor injection), you have to create your implementation of the ViewModelProvider.Factory
interface and use it to create view models with non-empty constructors.