Inject ViewModel using Dagger 2 + Kotlin + ViewModel

后端 未结 6 1377
-上瘾入骨i
-上瘾入骨i 2021-02-07 07:07
class SlideshowViewModel : ViewModel() {

@Inject lateinit var mediaItemRepository : MediaItemRepository

fun init() {
    What goes here?
}

So I\'m tr

6条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-07 07:32

    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)
          }
    
        }
    
    

提交回复
热议问题