1

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.

Some random IT boy
  • 7,569
  • 2
  • 21
  • 47
  • https://androidx.tech/artifacts/lifecycle/lifecycle-viewmodel/2.5.0-alpha04-source/androidx/lifecycle/viewmodel/InitializerViewModelFactory.kt.html - `initializer` is not a Kotlin language keyword here but part of a DSL to allow you to pass a lambda used to create an instance of the ViewModel class – Ken Wolf Mar 18 '23 at 14:37
  • Hover your cursor over it in Android Studio, and it will show you the documentation for that function. – Tenfour04 Mar 18 '23 at 15:10

2 Answers2

0

It's similar to the constructor logic in other object-oriented programming languages. I did some research. I found the description of the same code on a different site. You can go down and see after line 9. A code written for the first runtime after the display is started.

Scroll down to 9

Efekan
  • 1
  • 1
  • Thank you a lot! It helps when you think of this problem not as part of android/kotlin itself but object-oriented programming itself! – Евгений s Mar 20 '23 at 18:54
0

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

cactustictacs
  • 17,935
  • 2
  • 14
  • 25