Both of them do the same thing, but there is a discriminative advantage for the first one. Kotlin property delegation uses the idea of Lazy Initialization
. On Wikipedia you can find a brief definition for it:
In computer programming, lazy initialization is the tactic of delaying the creation of an object, the calculation of a value, or some other expensive process until the first time it is needed. It is a kind of lazy evaluation that refers specifically to the instantiation of objects or other resources.
Therefore, when you use the first approach you mentioned, you take the advantage of lazy properties. It means that the ViewModel instance becomes created only upon first access.
Given below code as an example:
class YourFragment : Fragment() {
private val viewModel: CharactersViewModel by viewModels()
// other codes ...
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
// doing some view initialization ...
viewModel.someLiveData.observe(viewLifecycleOwner) {
// ...
}
}
}
If viewModel.someLiveData.observe(viewLifecycleOwner)
is the first time that the viewModel
field is touched, the instantiation of it will happen there. (creation of a CharactersViewModel
instance)
So, using lazy initialization of objects like the view model reduces the start-up impact of your fragment which leads to faster loading and showing its content as opposed to direct initialization of them.