class SlideshowViewModel : ViewModel() {
@Inject lateinit var mediaItemRepository : MediaItemRepository
fun init() {
What goes here?
}
So I\'m tr
Assuming you have a Repository
class that can be injected by Dagger and a MyViewModel
class that has a dependency on Repository
defined as such:
class Repository @Inject constructor() {
...
}
class MyViewModel @Inject constructor(private val repository: Repository) : ViewModel() {
...
}
Now you can create your ViewModelProvider.Factory
implementation:
class MyViewModelFactory @Inject constructor(private val myViewModelProvider: Provider) : ViewModelProvider.Factory {
@Suppress("UNCHECKED_CAST")
override fun create(modelClass: Class): T {
return myViewModelProvider.get() as T
}
}
Dagger setup does not look too complicated:
@Component(modules = [MyModule::class])
interface MyComponent {
fun inject(activity: MainActivity)
}
@Module
abstract class MyModule {
@Binds
abstract fun bindsViewModelFactory(factory: MyViewModelFactory): ViewModelProvider.Factory
}
Here's the activity class (might be fragment as well), where the actual injection takes place:
class MainActivity : AppCompatActivity() {
@Inject
lateinit var factory: ViewModelProvider.Factory
lateinit var viewModel: MyViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// retrieve the component from application class
val component = MyApplication.getComponent()
component.inject(this)
viewModel = ViewModelProviders.of(this, factory).get(MyViewModel::class.java)
}
}