You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

CoroutineExceptionHandler搭配ViewModelScope和Koin使用时报空指针如何解决?

问题根源

Kotlin 类的初始化严格按照代码编写的从上到下顺序执行:先处理主构造参数赋值,再按顺序执行属性初始化、init代码块。
你当前的ViewModel代码中,init块写在了exceptionHandler属性定义的前面,当init块调用fetchDevices()时,exceptionHandler还未完成初始化,值为null。而viewModelScope.launch要求传入的CoroutineContext参数为非空类型,因此触发了报错日志里的空指针异常,同时导致Koin无法正常创建ViewModel实例。
另外你提供的Koin模块代码存在语法错误,构造参数调用get()后缺少右括号,也会导致异常。

修复方案
  1. 调整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) {
            // 你的业务逻辑
        }
    }
}
  1. 修复Koin模块的语法错误:
val viewModelModule = module {
    // 补全get()的右括号
    viewModel { ActivateDeviceViewModel(get()) }
}

内容的提问来源于stack exchange,提问作者Tomas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 17:54:04