Photo by Shahadat Rahman on Unsplash

Android ViewModel, LiveData, Repository and DI — Complete and Super Quick

Chris Ribetti
2 min readJan 12, 2020

--

The code below gives you a complete Android MVVM + LiveData + Repository + DI implementation. I assume that you know about all of these.

You just want to know how to fit the pieces together really easily.

The code below flows as follows. I think going from simple concepts to more complex concepts is good, so I go from Data to Activity. There’s a Data class that has the data. There’s a Service that gets the data. There’s a Repository that hands over the data to the LiveData object, which is passed through the DataViewModel object onto the Activity. The code even has all the dependency injection included to make testing a breeze!

data class Data(val first: Int = 0, val second: Float = 0.0f)class Service {
fun getData(): Data { /* via Retrofit etc. */ return Data() }
}
class Repository(private val service: Service) {
val liveData = MutableLiveData<Data>()
fun getData() { liveData.value = service.getData() }
}
class DataViewModel(private val repository: Repository): ViewModel() {
val liveData: LiveData<Data> = repository.liveData
fun getData() { repository.getData() }
}
@Suppress("UNCHECKED_CAST")
class ViewModelFactory constructor(private val repository: Repository): ViewModelProvider.Factory {
override fun <T : ViewModel> create(modelClass: Class<T>)
: T = DataViewModel(repository) as T
}
object Injection {
val service: Service by lazy { Service() }
val repository: Repository by lazy { Repository(service) }
val viewModelFactory: ViewModelFactory by lazy {
ViewModelFactory(repository)
}
}
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val model: DataViewModel by viewModels {
Injection.viewModelFactory
}
model.liveData.observe(this, Observer<Data> { result ->
println(result) // update UI
})
model.getData() // get the data and println() will be called
}
}

I hope the code is self-explanatory. Then, in Android Studio:

  1. Create a new Android project with an empty activity.
  2. Add implementation 'androidx.fragment:fragment-ktx:1.1.0' to build.gradle. This allows the use of by viewModels.
  3. Copy-paste the above code into MainActivity.
  4. Get the IDE to resolve imports inMainActivity.
  5. It’ll run.

Happy coding!

--

--

Chris Ribetti

Developer at JPMorgan Chase. Everything Android, Math, Quantum, Physics, Cosmology, Maps and yes, Mainframe.