Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does kotlin use this by delegate to instantiate the viewmodel

Tags:

I was reading through the google android architecture example and came across this.Can someone explain to me how this delegate works?

private val viewModel by viewModels<TasksViewModel> { getViewModelFactory() }

where getViewModelFactory is an extension method that returns a ViewModelFactory and TasksViewModel is an instance of ViewModel()

The way that I read this is similar to:

private val viewModel: TasksViewModel by Fragment.ViewModel(ViewModelFactory)

can someone elaborate on if my understanding is correct.

like image 960
stegnerd Avatar asked Sep 25 '19 21:09

stegnerd


People also ask

How does kotlin delegate work?

Kotlin Vocabulary: Delegates Delegation is a design pattern in which an object handles a request by delegating to a helper object, called the delegate. The delegate is responsible for handling the request on behalf of the original object and making the results available to the original object.

What is the correct way to access the shared ViewModel using the kotlin property delegate approach?

What is the correct way to access the shared view model using the Kotin property delegate approach? Enter one or more words to complete the sentence. Use a LiveData to return a different LiveData instance based on the value of another instance.

Why do we use delegation in Kotlin?

Kotlin supports “delegation” design pattern by introducing a new keyword “by”. Using this keyword or delegation methodology, Kotlin allows the derived class to access all the implemented public methods of an interface through a specific object.


1 Answers

by viewModels(...) is part of fragment-ktx library, it's a convienience short hand for creating a lazy delegate obtaining ViewModels.

// creates lazy delegate for obtaining zero-argument MyViewModel
private val viewModel : MyViewModel by viewModels()
// it's functionally equal to:
private val viewModel by lazy {
    ViewModelProvider(this).get(MyViewModel::class.java)
}

// with factory:
private val viewModel : MyViewModel by viewModels { getViewModelFactory() }
// is equal to:
private val viewModel by lazy {
    ViewModelProvider(this, getViewModelFactory()).get(MyViewModel::class.java)
}
like image 119
Pawel Avatar answered Oct 06 '22 08:10

Pawel