Welcome to this **Koin Tutorial** for Android developers! In this step-by-step video, we’ll guide you through how to **set up a Repository and ViewModel using Koin** — a lightweight and powerful dependency injection (DI) framework made specifically for Kotlin.
If you're working with the **MVVM architecture** and want to learn how to manage dependencies in a clean, testable way, this tutorial is perfect for you. We’ll cover everything from configuring your `build.gradle` to injecting your `Repository` into a `ViewModel` using **Koin's DI magic**.
---
### What You’ll Learn:
How to install and set up Koin in your Android project
How to create and inject a Repository using Koin
How to create a ViewModel and inject dependencies
How to define and load Koin modules
How to use ViewModel in Activities or Fragments
---
### Prerequisites:
- Familiarity with Kotlin and Android Studio
- Basic understanding of MVVM architecture
- A working Android project to integrate Koin with
---
### Tutorial Breakdown:
1. **Add Koin Dependencies** to your `build.gradle`:
```kotlin
implementation "io.insert-koin:koin-android:3.5.3"
implementation "io.insert-koin:koin-androidx-viewmodel:3.5.3"
```
2. **Create a Repository Class**:
```kotlin
class UserRepository {
fun getUser(): String = "John Doe"
}
```
3. **Create a ViewModel** and Inject the Repository:
```kotlin
class MainViewModel(private val userRepository: UserRepository) : ViewModel() {
fun getUsername(): String = userRepository.getUser()
}
```
4. **Define Your Koin Modules**:
```kotlin
val appModule = module {
single { UserRepository() }
viewModel { MainViewModel(get()) }
}
```
5. **Start Koin in Application Class**:
```kotlin
class MyApplication : Application() {
override fun onCreate() {
super.onCreate()
startKoin {
androidContext(this@MyApplication)
modules(appModule)
}
}
}
```
6. **Inject ViewModel in Activity/Fragment**:
```kotlin
class MainActivity : AppCompatActivity() {
private val mainViewModel: MainViewModel by viewModel()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
println(mainViewModel.getUsername())
}
}
```
---
### Bonus Tips:
- Koin’s `by viewModel()` makes injection seamless for Android components.
- Use `single` for shared instances and `factory` if you need new ones each time.
- Easily replace implementations for testing by swapping modules.
---
Don't forget to **like**, **comment**, and **subscribe** for more Kotlin + Android Dev content!
---
#Koin #KoinTutorial #Kotlin #AndroidDevelopment #ViewModel #RepositoryPattern #MVVM #DependencyInjection #KoinViewModel #KoinRepository #KotlinAndroid #AndroidStudio #AndroidArchitecture #AndroidTips