Cannot use "by viewModel" from Activity
I want to inject a ViewModel for an Activity, so I tried this. But it was failed, Android Studio cannot find reference of it.
private val mainViewModel: MainViewModel by viewModel()
My activity extends AppCompatActivity
, and gradle dependencies includes these libraries:
implementation 'androidx.core:core-ktx:1.3.2'
def koin_version = '2.2.1'
implementation "org.koin:koin-android:$koin_version"
implementation "org.koin:koin-androidx-scope:$koin_version"
implementation "org.koin:koin-androidx-viewmodel:$koin_version"
implementation "org.koin:koin-androidx-fragment:$koin_version"
implementation "androidx.lifecycle:lifecycle-viewmodel-savedstate:$koin_version"
What I tried:
The code below is working, but I want to use new default "SavedStateHandle" feature of Koin 2.2.0.
private val mainViewModel: MainViewModel by inject()
I found this code was already included, Android Studio cannot find it.
ActivityExt.kt:
inline fun <reified T : ViewModel> ComponentActivity.viewModel(
qualifier: Qualifier? = null,
noinline state: BundleDefinition? = null,
noinline owner: ViewModelOwnerDefinition = { from(this, this) },
noinline parameters: ParametersDefinition? = null,
): Lazy<T> {
return lazy(LazyThreadSafetyMode.NONE) {
getViewModel(qualifier, state, owner, parameters)
}
}
In Fragment, both viewModel
and sharedViewModel
works fine.
private val viewModel by viewModel<SearchViewModel>()
private val mainViewModel by sharedViewModel<MainViewModel>()
Question: What is the best way to inject ViewModel in Activity with Koin 2.2.0+ version?
I added this manually, and it works fine.
import org.koin.androidx.viewmodel.ext.android.viewModel