Search code examples
androidkotlinfactoryinitializerviewmodelfactory

What is "initializer" in android studio?


I have a program from official android tutorials about creating a database. The program has lots of viewmodels which I guess are instantiated in viewModelFactory. But what does the keyword "initializer" mean? I didn't find any information explaining what it is. Here's a piece of the code

object AppViewModelProvider {

    val Factory = viewModelFactory {
      
        initializer {
            ItemEditViewModel(
                this.createSavedStateHandle(),
                inventoryApplication().container.itemsRepository
            )
        }
       ...
}

I searched for the relevent information on the android studio site itself, but there were no use.


Solution

  • You should probably read this section on creating ViewModels with dependencies.

    If you scroll down to the ViewModels with CreationExtras section (and make sure you're looking at the Kotlin version of the code), you can see how you need to create a ViewModelProvider.Factory to enable passing dependencies when requesting a VM. And that involves overriding a create function with a bunch of boilerplate code, which allows you to access things you need to correctly build your ViewModel.

    Below that is an example of the ViewModel Factory DSL which allows you to replace this boilerplate with viewModelFactory and initializer functions, which are much more concise and allow you easier access to those extras you need to create your VM.

    (And if you look at the Java version of the first bit of code, you'll see how that uses a ViewModelInitializer which is similar to that second Kotlin example, but without the convenience of the DSL syntax. And below that it explains how this initializer approach was introduced with 2.5.0, and before that you had to create the factory with the overridden create function and all its boilerplate).