Advanced ViewModels (part I): Dependencies and Passing parameters.

Lucas Nobile
2 min readSep 9, 2020

--

ViewModel as the bridge between the View and the Model.

TL;DR: We can pass parameters to our ViewModel, use it as a data holder, also to share data between Fragments, and to persist its state across process recreation.

Update 9/15/2020: I decided to create a multi-part series about this topic since there will be more about this journey on MVVM architecture and ViewModels for sure 😉

Declaring dependencies

We will be using the following dependencies from lifecycle:

// ViewModel
implementation “androidx.lifecycle:lifecycle-viewmodel-ktx:$lifecycle_version”
// LiveData
implementation “androidx.lifecycle:lifecycle-livedata-ktx:$lifecycle_version”
// Saved state module for ViewModel
implementation “androidx.lifecycle:lifecycle-viewmodel-savedstate:$lifecycle_version”

And for fragment-ktx:

// Fragment KTX
implementation “androidx.fragment:fragment-ktx:$fragment_version”

Passing parameters

We can pass parameters to our ViewModel’s constructor as we are used to do for any class. However, to be able to handle that param we will need a Factory within our ViewModel:

import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.thenewsapp.data.NewsService
class NewsViewModel(private val newsService: NewsService) : ViewModel() {// My awesome stuffclass Factory(private val newsService: NewsService) : ViewModelProvider.Factory {@Suppress("UNCHECKED_CAST")
override fun <T : ViewModel?> create(modelClass: Class<T>): T {
return NewsViewModel(newsService) as T
}
}
}

Then, in our View (Fragment/Activity) we will be creating our ViewModel this way:

private val viewModel: NewsViewModel by viewModels { NewsViewModel.Factory(newsService) }

Per documentation, by viewModels is a property delegate to get a reference to the ViewModel scoped to this Fragment.

Let me share with you all the repo:

And my tech talk about Advanced ViewModels on Android for GDG Córdoba, Argentina (in Spanish):

Please, continue reading the next posts in this multi-part series for more tips regarding advanced ViewModels 🙌

--

--