Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

429
Views
View model initialization using "by viewModels()" vs "ViewModelProvider(this).get(ViewModel::class.java)" in android

We can initialize the ViewModel class using

private val viewModel: CharactersViewModel by viewModels()

or

viewModel = ViewModelProvider(this).get(CharactersViewModel::class.java)

Herer CharactersViewModel is our ViewModel class. My question is when to use which? Do both contain the same purpose? I have read the android official documentation of ViewModel.The documentation says by viewModels() Kotlin property delegate. But unfortunately failed to understand it. Can anyone help me understand this?

over 4 years ago · Hanz Gallego
3 answers
Answer question

0

To add to the already mentioned answers,

The lateinit modifier tells the type-checker that a var property will be initialised "by magic" before it is used, and so does not need to be given a nullable type. It prevents the type checker helping you initialise properties correctly. Instead, programming errors in initialisation are reported by exceptions later at runtime.

It is intended for when Kotlin code is interfacing with legacy Java frameworks that use reflection to poke values into fields behind the back of the type checker and visibility modifiers.

We should try to avoid lateinit in our code, if possible, in this case you should use

private val viewModel: CharactersViewModel by viewModels()
over 4 years ago · Hanz Gallego Report

0

Those two statements are equal.

The Kotlin keyword by simply saves you some code, saves you the pain of using reflection to access your VM and looks way cleaner, if you as me.

Either or should do the job for ya :)

over 4 years ago · Hanz Gallego Report

0

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.

over 4 years ago · Hanz Gallego Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!