Getting started with Android Architecture & ViewModel
Let’s start with Koin on a Android app with ViewModel feature
This tutorial lets you write an Android/Kotlin application and use Koin inject and retrieve your components and ViewModel.
Get the code
Checkout the project directly on Github or download the zip file
Add the Koin Android dependency like below:
Let’s create a HelloRepository to provide some data:
Let’s create a ViewModel class, for consuming this data:
Writing the Koin module
module function to declare a module. Let’s declare our first component:
Note: we declare our MyViewModel class as a
viewModel in a
module. Koin will give a
MyViewModel to the lifecycle ViewModelFactory and help bind it to the current component.
Now that we have a module, let’s start it with Koin. Open your application class, or make one (don’t forget to declare it in your manifest.xml). Just call the
MyViewModel component will be created with
HelloRepository instance. To get it into our Activity, let’s inject it with the
by viewModel() delegate injector:
The by viewModel() function allows us to retrieve a ViewModel instance from Koin, linked to the Android ViewModelFactory.
The getViewModel() function is here to retrieve directly an instance (non lazy)
You have finished this starting tutorial. Below are some topics for further reading:
Also other Android getting started project: