viewModels

inline fun <VM : ViewModel> Fragment.viewModels(noinline ownerProducer: () -> ViewModelStoreOwner = { this }, noinline extrasProducer: () -> CreationExtras? = null, noinline factoryProducer: () -> ViewModelProvider.Factory? = null): Lazy<VM>

Returns a property delegate to access ViewModel by default scoped to this Fragment:

class MyFragment : Fragment() {
val viewmodel: MyViewModel by viewModels()
}

Custom ViewModelProvider.Factory can be defined via factoryProducer parameter, factory returned by it will be used to create ViewModel:

class MyFragment : Fragment() {
val viewmodel: MyViewModel by viewModels { myFactory }
}

Default scope may be overridden with parameter ownerProducer:

class MyFragment : Fragment() {
val viewmodel: MyViewModel by viewModels ({requireParentFragment()})
}

This property can be accessed only after this Fragment is attached i.e., after Fragment.onAttach(), and access prior to that will result in IllegalArgumentException.