You need to enable JavaScript to run this app. Kotlin协程+Retrofit2开发遇MutableLiveData空指针崩溃如何解决?
优惠活动
大模型
产品
解决方案
定价
更多

Kotlin协程+Retrofit2开发遇MutableLiveData空指针崩溃如何解决?

问题排查与解决方案

问题1:接口动态ID参数实现

问题原因

当前代码中DataSource层把请求ID硬编码为固定值"2",且从DataSource到Repository到ViewModel的整条调用链路没有预留ID传参入口,无法动态修改参数值。

修复方案

逐层补充ID传参入口,同时优化Retrofit接口适配协程,移除冗余的Call执行逻辑:

  1. 服务接口改造,改为挂起函数适配协程
interface AltKategoriService {

    @GET("alt_kategoriler/" + Const.READ_URL_PIECE)
    suspend fun getId(@Query("id") id: String?): Resource<AltKategorilerResponse>

    companion object{
        fun build(): AltKategoriService {
            val interceptor = HttpLoggingInterceptor()
            interceptor.level = HttpLoggingInterceptor.Level.BODY

            val okHttpClient = OkHttpClient.Builder()
                .addInterceptor(interceptor)
                .build()

            val retrofit = Retrofit.Builder()
                .addConverterFactory(GsonConverterFactory.create())
                .baseUrl(Const.BASE_URL)
                .client(okHttpClient)
                .build()

            return retrofit.create(AltKategoriService::class.java)
        }
    }
}
  1. DataSource层补充ID参数
// 先修改DataSource接口定义
interface AltKategorilerDataSource {
    fun getSubCategories(id: String): Flow<Resource<AltKategorilerResponse>>
}

// 实现类对应修改
class RemoteAltKategorilerDataSource : AltKategorilerDataSource {
    override fun getSubCategories(id: String): Flow<Resource<AltKategorilerResponse>> = flow {
        try {
            emit(Resource.Loading())
            val response = AltKategoriService.build().getId(id)
            emit(response)
        } catch (ex: Exception) {
            emit(Resource.Error(ex))
            ex.printStackTrace()
        }
    }
}
  1. Repository层同步补充传参入口
class AltKategoriRepository {
    private val remoteDataSource = RemoteAltKategorilerDataSource()
    fun getSubCategories(id: String) = remoteDataSource.getSubCategories(id)
}
  1. 调用时直接传入需要的ID值即可实现动态查询,比如需要查询id=3时调用getSubCategories("3")即可。

问题2:MutableLiveData空指针崩溃

问题原因

触发崩溃的核心原因有三个:

  • 代码中使用非空断言!!强转resource.data和resource.throwable,当这两个值为空时直接触发空指针
  • 采用Flow.asLiveData().observeForever()的写法,没有手动移除观察者,ViewModel销毁后观察者仍收到事件时会调用空对象的postValue方法
  • loading被定义为可空类型,额外增加了空风险

修复方案

优化ViewModel层逻辑,移除冗余的LiveData转换和永久观察者,用Flow直接收集,同时替换所有非空断言为安全调用:

class SubCategoryViewModel: ViewModel() {
    private val altKategoriRepository = AltKategoriRepository()

    // 所有LiveData定义为非空,初始化即赋值,消除空风险
    val loading = MutableLiveData<Boolean>()
    val altKategoriLiveData = MutableLiveData<AltKategorilerResponse>()
    val error = MutableLiveData<Throwable>()

    init {
        // 若需要默认加载id=2的数据保留该调用,不需要可删除
        getSubCategories("2")
    }

    fun getSubCategories(id: String) = viewModelScope.launch {
        altKategoriRepository.getSubCategories(id).collect { resource ->
            when (resource.status) {
                ResourceStatus.LOADING -> {
                    loading.postValue(true)
                }
                ResourceStatus.SUCCESS -> {
                    // 安全调用,仅当data非空时执行后续逻辑
                    resource.data?.let { data ->
                        Log.e("Message", data.toString())
                        altKategoriLiveData.postValue(data)
                    }
                    loading.postValue(false)
                }
                ResourceStatus.ERROR -> {
                    // 安全调用,仅当throwable非空时执行后续逻辑
                    resource.throwable?.let { throwable ->
                        error.postValue(throwable)
                    }
                    loading.postValue(false)
                }
            }
        }
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.16 01:27:06