liujingxing / rxhttp

🔥🔥🔥 Based on OkHttp encapsulation, support Kotlin Coroutines、RxJava2、RxJava3; 30s to get started.
https://juejin.im/post/5ded221a518825125d14a1d4
Apache License 2.0
3.74k stars 457 forks source link

解析器onParse方法返回可空类型时,使用ksp编译异常 #456

Closed gudao20080 closed 1 year ago

gudao20080 commented 1 year ago
  1. 纯Kotlin项目, 准备用ksp 替代 kapt
  2. rxHttpVersion = "3.1.1", plugins { id ("com.android.application") version "8.0.2" apply false id ("com.android.library") version "8.0.2" apply false id ("org.jetbrains.kotlin.android") version "1.8.22" apply false id("com.google.devtools.ksp") version "1.8.22-1.0.11" apply false }
  3. 使用kapt编译通过, ksp报错,如下: image image
liujingxing commented 1 year ago

自定义解析器截图看下,应该是你的范型声明了可空类型,删掉就好

gudao20080 commented 1 year ago
package com.jinmaoedu.smartclass.teacher.net.response

import rxhttp.wrapper.annotation.Parser
import rxhttp.wrapper.exception.ParseException
import rxhttp.wrapper.parse.TypeParser
import rxhttp.wrapper.utils.convertTo
import java.io.IOException
import java.lang.reflect.Type

/**
 * 输入T,输出T,并对code统一判断
 * User: ljx
 * Date: 2018/10/23
 * Time: 13:49
 *
 * 如果使用协程发送请求,wrappers属性可不设置,设置了也无效
 */
@Parser(name = "Response")
open class ResponseParser<T> : TypeParser<T> {
        /**
     * 此构造方法可适用任意Class对象,但更多用于带泛型的Class对象,如:List<List<Student>>>
     *
     * 如Java环境中调用
     * toObservable(new ResponseParser<List<List<Student>>>(){})
     * 等价于kotlin环境下的
     * toObservableResponse<List<List<Student>>>()
     *
     * 注:此构造方法一定要用protected关键字修饰,否则调用此构造方法将拿不到泛型类型
     */
    protected constructor() : super()

    /**
     * 该解析器会生成以下系列方法,前3个kotlin环境调用,后4个Java环境调用,所有方法内部均会调用本构造方法
     * toFlowResponse<T>()
     * toAwaitResponse<T>()
     * toObservableResponse<T>()
     * toObservableResponse(Type)
     * toObservableResponse(Class<T>)
     * toObservableResponseList(Class<T>)
     * toObservableResponsePageList(Class<T>)
     *
     * Flow/Await下 toXxxResponse<PageList<T>> 等同于 toObservableResponsePageList(Class<T>)
     */
    constructor(type: Type) : super(type)

    @Throws(IOException::class)
    override fun onParse(response: okhttp3.Response): T? {
        val data: ScResponse<T> = response.convertTo(ScResponse::class, *types)
        var t = data.data //获取data字段
//        if (t == null && types[0] === String::class.java) {
//            /*
//             * 考虑到有些时候服务端会返回:{"errorCode":0,"errorMsg":"关注成功"}  类似没有data的数据
//             * 此时code正确,但是data字段为空,直接返回data的话,会报空指针错误,
//             * 所以,判断泛型为String类型时,重新赋值,并确保赋值不为null
//             */
//            @Suppress("UNCHECKED_CAST")
//            t = data.msg as T
//        }
        if (data.code != 0 || t == null) { //code不等于0,说明数据不正确,抛出异常
            throw ParseException(data.code.toString(), data.msg, response)
        }
        return t

    }
}

照你的抄的,转了一下kotlin, 修改了下

liujingxing commented 1 year ago

onParse方法返回类型T?改为T就好,下个版本会适配该问题