CoroutineExceptionHandler搭配ViewModelScope和Koin使用时报空指针如何解决?
问题根源
Kotlin 类的初始化严格按照代码编写的从上到下顺序执行:先处理主构造参数赋值,再按顺序执行属性初始化、init代码块。
你当前的ViewModel代码中,init块写在了exceptionHandler属性定义的前面,当init块调用fetchDevices()时,exceptionHandler还未完成初始化,值为null。而viewModelScope.launch要求传入的CoroutineContext参数为非空类型,因此触发了报错日志里的空指针异常,同时导致Koin无法正常创建ViewModel实例。
另外你提供的Koin模块代码存在语法错误,构造参数调用get()后缺少右括号,也会导致异常。
修复方案
- 调整ViewModel代码顺序,将异常处理器的初始化放到init块之前:
class ActivateDeviceViewModel constructor( private val activateDeviceUseCase: ActivateDeviceUseCase, ) : ViewModel() { // 先初始化异常处理器 private val exceptionHandler = CoroutineExceptionHandler { coroutineContext, throwable -> Timber.tag("test").d(throwable) } init { fetchDevices() } private fun fetchDevices() { viewModelScope.launch(exceptionHandler) { // 你的业务逻辑 } } }
- 修复Koin模块的语法错误:
val viewModelModule = module { // 补全get()的右括号 viewModel { ActivateDeviceViewModel(get()) } }
内容的提问来源于stack exchange,提问作者Tomas
相关产品推荐
相关产品推荐

