我正在尝试使用Jetpack tutorial在片段和活动之间创建共享注入视图模型。
共享视图模型成功注入到父级 MyActivity 中,但是当渲染子级时,由于依赖注入失败,应用程序崩溃。我在下面提供了创建问题的代码。
提供会话管理器:
@InstallIn(ApplicationComponent::class)
@Module
class AppModule {
@Provides
@Singleton
fun provideSessionManager(
networkClient: NetworkClient
): SessionManager {
return SessionManager(networkClient)
}
}
注入共享视图模型:
class SharedViewModel @ViewModelInject constructor(
private var sessionManager: SessionManager
) : ViewModel() {
var name = MutableLiveData<String>("Shared View Model")
}
并且被父活动和子片段使用。
class MyActionFragment() : Fragment() {
private val viewModel: SharedViewModel by viewModels()
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
Timber.d("View Model Name 1: ${viewModel.name.value}") // This line crashes
}
}
class MyActivity : AuthenticatedBaseActivity() {
private val viewModel: SharedViewModel by viewModels()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
Timber.d("View Model Name 2: ${viewModel.name.value}") // This line prints
}
}
但是,当代码运行时,请注意活动创建了 ViewModel 并访问了它的值,但是当片段尝试这样做时,应用程序崩溃了:
**D/MyActivity: View Model Name 2: Shared View Model**
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.xxx.xxx, PID: 16630
java.lang.RuntimeException: Cannot create an instance of class com.xxx.xxx.ui.main.SharedViewModel
at androidx.lifecycle.ViewModelProvider$NewInstanceFactory.create(ViewModelProvider.java:221)
at androidx.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.java:278)
at androidx.lifecycle.SavedStateViewModelFactory.create(SavedStateViewModelFactory.java:106)
at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:185)
at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:150)
at androidx.lifecycle.ViewModelLazy.getValue(ViewModelProvider.kt:54)
at androidx.lifecycle.ViewModelLazy.getValue(ViewModelProvider.kt:41)
at com.xxx.xxx.ui.main.MyActionFragment.getViewModel(Unknown Source:2)
at com.xxx.xxx.ui.main.MyActionFragment.onActivityCreated(**MyActionFragment.kt:140**)
at androidx.fragment.app.Fragment.performActivityCreated(Fragment.java:2718)
此外,当我删除注入的 Hilt 依赖项时sessionManager
,片段和视图模型的创建没有问题。
没有运气就关注了这篇文章。
非常感谢有关使用共享模型的 Hilt 视图模型依赖注入的任何帮助!谢谢!