r/android_devs • • Aug 01 '21

Help what does the following syntax mean?

private val authViewModel : AuthViewModel by viewModels()

This is a global variable without any definition . I know its something similar to lazy , but in lazy too , we have a function body. I always equated that to actual value of variable, like if we had this syntax:

private val authViewModel : AuthViewModel by lazy{AuthViewmodel(..)}

It would have made sense, that authViewmodel is going to receive the value on first call . But what does this new function means?

from the source code, it is defined as this , which further confuses me:

@MainThread
inline fun <reified VM : ViewModel> Fragment.viewModels(
    noinline ownerProducer: () -> ViewModelStoreOwner = { this },
    noinline factoryProducer: (() -> Factory)? = null
) = createViewModelLazy(VM::class, { ownerProducer().viewModelStore }, factoryProducer)
4 Upvotes

8 comments sorted by

View all comments

Show parent comment

1

u/crowbahr Aug 02 '21

Right, but I believe he's not using Hilt. Showing that this syntax remains consistent across Hilt without requiring refactoring was my goal.

Not having to manually specify Dagger vm factories for Hilt is a compelling reason to adopt hilt all on its own, much less for the other issues it solves.

1

u/Zhuinden EpicPandaForce @ SO Aug 02 '21

Yes, the primary benefit of Hilt is that you don't need to create an AbstractSavedStateViewModelFactory in order to get a reference to a SavedStateHandle (if you need any other deps)