How to use Koin in an Android app?

Koin is a popular dependency injection library for Kotlin projects, making it easier to manage dependencies in your Android applications. This guide will help you to integrate Koin into your Android app, simplifying the process of dependency management.

Steps to Use Koin in Your Android App

  1. Add Koin Dependencies: Update your app's build.gradle file to include the Koin dependencies.
  2. Create Koin Modules: Define modules where you declare your dependencies.
  3. Start Koin: Initialize Koin in your application class.
  4. Inject Dependencies: Use Koin to inject your dependencies into the necessary components.

Example Implementation

// 1. Add Koin dependencies in build.gradle dependencies { implementation "io.insert-koin:koin-androidx-viewmodel:" implementation "io.insert-koin:koin-android:" } // 2. Create a Koin module val appModule = module { viewModel { MyViewModel(get()) } single { MyRepository() } } // 3. Start Koin in your Application class class MyApplication : Application() { override fun onCreate() { super.onCreate() startKoin { // declare modules modules(appModule) } } } // 4. Injecting dependencies in an Activity class MyActivity : AppCompatActivity() { private val myViewModel: MyViewModel by viewModel() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Use myViewModel... } }

Koin dependency injection Android app Koin setup Koin tutorial