Inject ViewModels

Injecting ViewModels

To inject a view model use @ViewModel annotation

Activity
@ViewModel
lateinit var vm:MyViewModel

Scimitar supports inheritance you can put Scimitar.bind(this) in a base class and not worry about it anymore, then all you need is to annotate the view models with @ViewModel

After that bind the Fragment or Activity using

Scimitar.bind(this)

ViewModelFactory

Most of times a custom view model factory is used, to support this Scimitar uses @ViewModelFactory annotation to know which factory to use when creating view models

Activity
@ViewModel
lateinit var vm:MyViewModel

@ViewModelFactory
lateinit var factory:ViewModelProvider.Factory

If you want to use the same ViewModelFactory use @ViewModelFactory("useAsDefault"=true), this causes Scimitar to use the same ViewModelFactory when creating view models.

BaseActivity

@ViewModelFactory("useAsDefault" = true)
lateinit var factory:ViewModelProvider.Factory

protected fun onCreate(Bundle savedInstanceState) {
    Scimitar.bind(this)
}

Last updated