我的功能很简单,
主线程:初始化变量->
背景线程:消防网络请求,将结果重新分配给前一个变量->
主线程:显示该变量
代码如下:
suspend fun createCity(context: Context, newCity: MutableLiveData<NewIdea>, mapBody: Map<String, String>, token: String) {
    lateinit var response: NewIdea
    try {
        withContext(Dispatchers.IO) {
            val map = generateRequestBody(mapBody)
            response = webservice.createIdea(tripId, map, "Bearer $token")
            getTrip(context, token)
        }
    } catch (e: Exception) {
        Log.e(TAG, e.message)
    }
    newCity.value = response
}但是有时候(实际上只发生了2次),crashlytics报告了这行newCity.value = response的崩溃
Fatal Exception: kotlin.UninitializedPropertyAccessException: lateinit property response has not been initialized
我真不明白那怎么会发生。这是从coroutine函数返回值的正确方法吗?
谢谢
发布于 2020-07-22 04:37:07
好的,如果try块失败了,那么就可能根本没有设置lateinit变量。您还应该将ui更新代码放在try块中,并分别处理Exception:
Sidenote: withContext经过很好的优化以返回值,因此您可以使用它。
suspend fun createCity(context: Context, newCity: MutableLiveData<NewIdea>, mapBody: Map<String, String>, token: String) {
    try {
        val response: NewIdea = withContext(Dispatchers.IO) {
            val map = generateRequestBody(mapBody)
           // does createIdea() first store it in var, then does getTrip(), then returns the result of createIdea() stored previously
            webservice.createIdea(tripId, map, "Bearer $token").also { getTrip(context, token) }  // ^withContext
        }
        newCity.value = response
    } catch (e: Exception) {
        Log.e(TAG, e.message)
    }
}一个快速提示(可选):您可以用一个withContext包装UI更新代码,该withContext在主线程中没有运行时将工作分派给Dispatchers.Main,而如果在main中运行什么都不做:
withContext(Dispatchers.Main.immediate) {
    val response: NewIdea = withContext(Dispatchers.IO) {
        val map = generateRequestBody(mapBody)
        // does createIdea() first store it in var, then does getTrip(), then returns the result of createIdea() stored previously
        webservice.createIdea(tripId, map, "Bearer $token").also { getTrip(context, token) }  // ^withContext
    }
    newCity.value = response
}https://stackoverflow.com/questions/63026140
复制相似问题