Shared ViewModel中lateinit变量未初始化致应用崩溃问题
解决ViewModel中lateinit变量后台回收后未初始化崩溃问题
当应用切换到后台并被系统回收内存时,关联的Activity和ViewModel会被销毁。重新回到应用时,系统会重建Activity与ViewModel实例,此时你之前在其他Fragment中初始化的previousPath并未被重新赋值,访问时就会触发kotlin.UninitializedPropertyAccessException异常。
解决方案
方案一:使用SavedStateHandle持久化状态
ViewModel通过SavedStateHandle可以自动处理进程销毁后的状态恢复,确保重建后能获取到之前的值:class ShareUserVM(private val savedStateHandle: SavedStateHandle) : ViewModel() { var previousPath: UserPreviousPath get() = savedStateHandle.get<UserPreviousPath>("previousPath") ?: UserPreviousPath.SIGN_IN set(value) = savedStateHandle.set("previousPath", value) }这样即使ViewModel被重建,
previousPath会从SavedStateHandle中恢复之前的赋值,不会出现未初始化的情况。方案二:替换lateinit为带默认值的变量
直接给变量设置默认初始值,彻底避免未初始化状态:class ShareUserVM : ViewModel() { var previousPath: UserPreviousPath = UserPreviousPath.SIGN_IN }若需要允许变量暂时未初始化,可改用可空类型并在访问时做安全判断:
// ViewModel修改 class ShareUserVM : ViewModel() { var previousPath: UserPreviousPath? = null } // EnterUserDetailsFragment中访问 shouldAuthenticate = sharedUserVM.previousPath?.let { it == UserPreviousPath.PROFILE } ?: false方案三:检查lateinit初始化状态(仅避免崩溃,不恢复状态)
在访问previousPath前先判断是否已初始化,避免崩溃,但无法恢复之前的状态:shouldAuthenticate = if (sharedUserVM::previousPath.isInitialized) { sharedUserVM.previousPath == UserPreviousPath.PROFILE } else { false // 根据业务需求设置兜底逻辑 }
内容的提问来源于stack exchange,提问作者Target
相关产品推荐
相关产品推荐

