How to inject view model with Koin in Android

Issue #359

app/build.gradle

1
2
3
implementation "org.koin:koin-core:$Version.koin"
implementation "org.koin:koin-androidx-scope:$Version.koin"
implementation "org.koin:koin-androidx-viewmodel:$Version.koin"

MyApplication.kt

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import android.app.Application
import org.koin.android.ext.koin.androidContext
import org.koin.android.ext.koin.androidLogger
import org.koin.androidx.viewmodel.dsl.viewModel
import org.koin.core.context.startKoin
import org.koin.dsl.module

class MyApplication: Application() {
var appModule = module {
single { MyRepo() }
viewModel { MyViewModel(get()) }
}

override fun onCreate() {
super.onCreate()

startKoin {
androidLogger()
androidContext(this@MyApplication)
modules(appModule)
}
}
}

MyFragment.kt

1
2
3
import org.koin.androidx.viewmodel.ext.android.viewModel

val viewModel: MyViewModel by viewModel()

Comments