未解决的对 Koin 的 sharedViewModel() 的引用
Unresolved reference to Koin's sharedViewModel()
我正在尝试将 sharedViewModel()
延迟注入我的 activity。出于某种原因,我的 IDE 无法解析引用。它可以成功解析 viewModel()
但不能解析 sharedViewModel()
。我可以将它添加到导入中,但我不能使用它。
依赖关系:
def koin_version = "2.0.1"
implementation "org.koin:koin-android:$koin_version"
implementation "org.koin:koin-androidx-scope:$koin_version"
implementation "org.koin:koin-androidx-viewmodel:$koin_version"
我是不是漏掉了什么?
问题是您正试图在 Activity
中使用 sharedViewModel()
。根据documentation:
The Activity sharing its ViewModel injects it with by viewModel() or
getViewModel(). Fragments are reusing the shared ViewModel with by
sharedViewModel().
要验证,您可以查看 FragmentExt.kt 的源代码,发现 sharedViewModel()
是 Fragment
扩展。因此,您应该使用 override val viewModel: PaymentViewModel by viewModel()
而不是 override val viewModel: PaymentViewModel by sharedViewModel()
我正在尝试将 sharedViewModel()
延迟注入我的 activity。出于某种原因,我的 IDE 无法解析引用。它可以成功解析 viewModel()
但不能解析 sharedViewModel()
。我可以将它添加到导入中,但我不能使用它。
依赖关系:
def koin_version = "2.0.1"
implementation "org.koin:koin-android:$koin_version"
implementation "org.koin:koin-androidx-scope:$koin_version"
implementation "org.koin:koin-androidx-viewmodel:$koin_version"
我是不是漏掉了什么?
问题是您正试图在 Activity
中使用 sharedViewModel()
。根据documentation:
The Activity sharing its ViewModel injects it with by viewModel() or getViewModel(). Fragments are reusing the shared ViewModel with by sharedViewModel().
要验证,您可以查看 FragmentExt.kt 的源代码,发现 sharedViewModel()
是 Fragment
扩展。因此,您应该使用 override val viewModel: PaymentViewModel by viewModel()
override val viewModel: PaymentViewModel by sharedViewModel()