Skip to content

Commit

Permalink
代码简化
Browse files Browse the repository at this point in the history
  • Loading branch information
liujingxing committed Jul 4, 2023
1 parent 8b3d246 commit 0e26b1f
Show file tree
Hide file tree
Showing 20 changed files with 178 additions and 222 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -115,8 +115,8 @@ public abstract class BaseRxHttp : ITag, CallFactory {
val errorHandler = RxJavaPlugins.getErrorHandler()
if (errorHandler == null) {
/*
RxJava2的一个重要的设计理念是:不吃掉任何一个异常, 即抛出的异常无人处理,便会导致程序崩溃
这就会导致一个问题,当RxJava2“downStream”取消订阅后,“upStream”仍有可能抛出异常,
RxJava的一个重要的设计理念是:不吃掉任何一个异常, 即抛出的异常无人处理,便会导致程序崩溃
这就会导致一个问题,当RxJava“downStream”取消订阅后,“upStream”仍有可能抛出异常,
这时由于已经取消订阅,“downStream”无法处理异常,此时的异常无人处理,便会导致程序崩溃
*/
RxJavaPlugins.setErrorHandler { LogUtil.logRxJavaError(it) }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ public class RxHttpGetEncryptParam : RxHttpNoBodyParam {
IOException::class,
IllegalArgumentException::class,
)
public fun <T : Point, R : CharSequence> test(
public final fun <T : Point, R : CharSequence> test(
a: MutableList<R>,
map: MutableMap<T, R>,
vararg b: Array<T>,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,19 +25,22 @@ public GetEncryptParam(String url) {
super(url, Method.GET);
}

public <T extends Point, R extends CharSequence> GetEncryptParam test(List<R> a, Map<T, R> map, T[]... b) throws IOException, IllegalArgumentException {
@SafeVarargs
public final <T extends Point, R extends CharSequence> GetEncryptParam test(List<R> a, Map<T, R> map, T[]... b) throws IOException, IllegalArgumentException {
return this;
}

@Override
public HttpUrl getHttpUrl() {
StringBuilder paramsBuilder = new StringBuilder(); //存储加密后的参数
for (KeyValuePair pair : getQueryParam()) {
//这里遍历所有添加的参数,可对参数进行加密操作
String key = pair.getKey();
Object value = pair.getValue();
//加密逻辑自己写

List<KeyValuePair> queryParam = getQueryParam();
if (queryParam != null) {
for (KeyValuePair pair : getQueryParam()) {
//这里遍历所有添加的参数,可对参数进行加密操作
String key = pair.getKey();
Object value = pair.getValue();
//加密逻辑自己写
}
}
String simpleUrl = getSimpleUrl(); //拿到请求Url
if (paramsBuilder.length() == 0) return HttpUrl.get(simpleUrl);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
* 1、解析器onParse方法返回类型泛型数量有且仅有1个
* 2、项目有依赖RxJava
* <p>
* 生效后,仅会在RxHttp类下生成toObservableXxx方法
* 生效后,仅会在BaseRxHttp类下生成toObservableXxx方法
*
* @return Class数组
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -177,8 +177,8 @@ fun List<ParameterSpec>.flapTypeParameterSpecTypes(
if (index == 0 && typeVariableNames.isNotEmpty() &&
(parameterSpec.isArrayType() || parameterSpec.isVarargType())
) {
typeVariableNames.mapTo(parameterSpecs) { typeVariableName ->
val variableName = "${typeVariableName.name.lowercase(Locale.getDefault())}Type"
typeVariableNames.mapTo(parameterSpecs) {
val variableName = "${it.name.lowercase(Locale.getDefault())}Type"
ParameterSpec.builder(variableName, K_TYPE).build()
}
} else {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,32 +10,34 @@ import com.squareup.kotlinpoet.TypeVariableName
* Time: 11:28
*/
//返回参数名列表, 多个参数用逗号隔开, 如: a, b, c
fun List<ParameterSpec>.toParamNames(): String {
val paramNames = StringBuilder()
forEachIndexed { index, parameterSpec ->
if (index > 0) paramNames.append(", ")
if (parameterSpec.isVararg()) paramNames.append("*")
paramNames.append(parameterSpec.name)
}
return paramNames.toString()
fun List<ParameterSpec>.toParamNames(
prefix: CharSequence = "",
postfix: CharSequence = ""
): String = joinToString(", ", prefix, postfix) {
if (it.isVararg()) "*${it.name}" else it.name
}

//获取泛型字符串 比如:<T> 、<K, V>等等
fun List<TypeVariableName>.getTypeVariableString(): String {
val type = StringBuilder()
forEachIndexed { i, typeVariableName ->
if (i > 0) type.append(", ")
type.append(typeVariableName.name)
}
return if (type.isEmpty()) "" else "<$type>"
val types = joinToString { it.name }
return if (types.isEmpty()) "" else "<$types>"
}

//返回 javaTypeOf<T>, javaTypeOf<K>等
fun List<TypeVariableName>.getTypeOfString(): String {
val type = StringBuilder()
forEachIndexed { i, typeVariableName ->
if (i > 0) type.append(", ")
type.append("javaTypeOf<${typeVariableName.name}>()")
fun List<TypeVariableName>.getTypeOfString(): String =
joinToString { "javaTypeOf<${it.name}>()" }


fun <T> Iterable<T>.joinToStringIndexed(
separator: CharSequence = ", ",
prefix: CharSequence = "",
postfix: CharSequence = "",
limit: Int = -1,
truncated: CharSequence = "...",
transform: ((Int, T) -> CharSequence)
): String {
var index = 0
return joinToString(separator, prefix, postfix, limit, truncated) {
transform.invoke(index++, it)
}
return type.toString()
}
Original file line number Diff line number Diff line change
Expand Up @@ -271,8 +271,8 @@ class BaseRxHttpGenerator(private val isAndroidPlatform: Boolean) {
${'$'}T<? super Throwable> errorHandler = ${'$'}T.getErrorHandler();
if (errorHandler == null) {
/*
RxJava2的一个重要的设计理念是:不吃掉任何一个异常, 即抛出的异常无人处理,便会导致程序崩溃
这就会导致一个问题,当RxJava2“downStream”取消订阅后,“upStream”仍有可能抛出异常,
RxJava的一个重要的设计理念是:不吃掉任何一个异常, 即抛出的异常无人处理,便会导致程序崩溃
这就会导致一个问题,当RxJava“downStream”取消订阅后,“upStream”仍有可能抛出异常,
这时由于已经取消订阅,“downStream”无法处理异常,此时的异常无人处理,便会导致程序崩溃
*/
RxJavaPlugins.setErrorHandler(${'$'}T::logRxJavaError);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.rxhttp.compiler.kapt

import com.rxhttp.compiler.common.joinToStringIndexed
import com.rxhttp.compiler.rxHttpPackage
import com.rxhttp.compiler.rxhttpClass
import com.squareup.javapoet.ArrayTypeName
Expand Down Expand Up @@ -47,9 +48,7 @@ class ParamsVisitor(private val logger: Messager) {
val methodList = ArrayList<MethodSpec>()
var method: MethodSpec.Builder
elementMap.forEach { (key, typeElement) ->
val rxHttpTypeNames = typeElement.typeParameters.map { parameterElement ->
TypeVariableName.get(parameterElement)
}
val rxHttpTypeNames = typeElement.typeParameters.map { TypeVariableName.get(it) }
val param = ClassName.get(typeElement)
val rxHttpName = "RxHttp${typeElement.simpleName}"
val rxHttpParamName = rxhttpClass.peerClass(rxHttpName)
Expand All @@ -59,37 +58,34 @@ class ParamsVisitor(private val logger: Messager) {
rxHttpParamName
}
//遍历public构造方法
typeElement.getPublicConstructors().forEach {
val parameterSpecs = ArrayList<ParameterSpec>() //构造方法参数
val methodBody = StringBuilder("return new \$T(new \$T(") //方法体
for ((index, element) in it.parameters.withIndex()) {
val parameterSpec = ParameterSpec.get(element)
parameterSpecs.add(parameterSpec)
if (index == 0 && parameterSpec.type.toString() == "java.lang.String") {
methodBody.append("format(" + parameterSpec.name + ", formatArgs)")
continue
} else if (index > 0) {
methodBody.append(", ")
typeElement.getPublicConstructors().forEach { element ->
//构造方法参数
val parameterSpecs = element.parameters.mapTo(ArrayList()) { ParameterSpec.get(it) }
val prefix = "return new \$T(new \$T("
val postfix = "))"
val methodBody = parameterSpecs
.joinToStringIndexed(", ", prefix, postfix) { index, it ->
if (index == 0 && it.type == STRING) {
"format(${it.name}, formatArgs)"
} else it.name
}
methodBody.append(parameterSpec.name)
val firstParamIsStringType = parameterSpecs.firstOrNull()?.type == STRING
if (firstParamIsStringType) {
val arrayAny = ArrayTypeName.of(TypeName.OBJECT)
parameterSpecs.add(ParameterSpec.builder(arrayAny, "formatArgs").build())
}
methodBody.append("))")
val methodSpec = MethodSpec.methodBuilder(key)
MethodSpec.methodBuilder(key)
.addModifiers(Modifier.PUBLIC, Modifier.STATIC)
.addParameters(parameterSpecs)
.addTypeVariables(rxHttpTypeNames)
.addParameters(parameterSpecs)
.varargs(firstParamIsStringType)
.addStatement(methodBody, rxHttpParamName, param)
.returns(methodReturnType)

if (parameterSpecs.firstOrNull()?.type.toString() == "java.lang.String") {
methodSpec.addParameter(ArrayTypeName.of(TypeName.OBJECT), "formatArgs")
.varargs()
}
methodSpec.addStatement(methodBody.toString(), rxHttpParamName, param)
.build()
.apply { methodList.add(this) }
}
val superclass = typeElement.superclass
var prefix = "((" + typeElement.simpleName + ")param)."
var prefix = "((${typeElement.simpleName})param)."
val rxHttpParam = when (superclass.toString()) {
"rxhttp.wrapper.param.BodyParam" -> rxhttpClass.peerClass("RxHttpBodyParam")
"rxhttp.wrapper.param.FormParam" -> rxhttpClass.peerClass("RxHttpFormParam")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package com.rxhttp.compiler.kapt

import com.rxhttp.compiler.J_ARRAY_TYPE
import com.rxhttp.compiler.J_TYPE
import com.rxhttp.compiler.common.joinToStringIndexed
import com.rxhttp.compiler.isDependenceRxJava
import com.rxhttp.compiler.rxhttpClass
import com.squareup.javapoet.AnnotationSpec
Expand Down Expand Up @@ -183,8 +184,8 @@ private fun List<ParameterSpec>.flapTypeParameterSpecs(
val firstParamType = parameterSpec.type
//对于kapt,数组类型或可变参数类型,得到的皆为数组类型,所以这里无需跟ksp一样判断可变参数类型
if (index == 0 && firstParamType == J_ARRAY_TYPE && typeVariableNames.isNotEmpty()) {
typeVariableNames.mapTo(parameterSpecs) { typeVariableName ->
val variableName = "${typeVariableName.name.lowercase(Locale.getDefault())}Type"
typeVariableNames.mapTo(parameterSpecs) {
val variableName = "${it.name.lowercase(Locale.getDefault())}Type"
ParameterSpec.builder(J_TYPE, variableName).build()
}
} else {
Expand Down Expand Up @@ -286,23 +287,15 @@ private fun MethodSpec.getToObservableXxxWrapFun(

//3、toObservableXxx方法体
val funBody = CodeBlock.builder()
val paramNames = StringBuilder()

//遍历参数,取出参数名
parameterSpecs.forEachIndexed { index, param ->
if (index > 0) paramNames.append(", ")
val paramNames = parameterSpecs.joinToStringIndexed(", ") { index, it ->
if (index < typeCount) {
/*
* Class类型参数,需要进行再次包装,最后再取参数名
* 格式:Type tTypeList = ParameterizedTypeImpl.get(List.class, tType);
*/
val variableName = "${param.name}$simpleName"
val expression = "\$T $variableName = \$T.get($simpleName.class, ${param.name})"
//Class类型参数,需要进行再次包装,最后再取参数名
val variableName = "${it.name}$simpleName"
//格式:Type tTypeList = ParameterizedTypeImpl.get(List.class, tType);
val expression = "\$T $variableName = \$T.get($simpleName.class, ${it.name})"
funBody.addStatement(expression, J_TYPE, parameterizedType)
paramNames.append(variableName)
} else {
paramNames.append(param.name)
}
variableName
} else it.name
}
val returnStatement = "return ${methodSpec.name}($paramNames)"
funBody.addStatement(returnStatement)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -123,11 +123,9 @@ class RxHttpExtensions {
val types = typeVariableNames.getTypeVariableString() // <T>, <K, V> 等
val typeOfs = typeVariableNames.getTypeOfString() // javaTypeOf<T>()等
val paramNames = parameterList.toParamNames() //构造方法参数名列表
val finalParams = when {
typeOfs.isEmpty() -> paramNames
paramNames.isEmpty() -> typeOfs
else -> "$typeOfs, $paramNames"
}
val finalParams = listOf(typeOfs, paramNames)
.filter { it.isNotEmpty() }
.joinToString()

if (typeVariableNames.isNotEmpty() && isDependenceRxJava()) { //对声明了泛型的解析器,生成kotlin编写的toObservableXxx方法
val toObservableXxxFunName = "toObservable$key"
Expand Down
Loading

0 comments on commit 0e26b1f

Please sign in to comment.