| | |
| | | |
| | | import android.content.Context |
| | | import android.util.Log |
| | | import com.dayu.baselibrary.business.BusinessProvider |
| | | import com.dayu.baselibrary.net.subscribers.ProgressSubscriber |
| | | import com.dayu.baselibrary.net.subscribers.SubscriberListener |
| | | import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers |
| | |
| | | |
| | | observable |
| | | .subscribeOn(Schedulers.io()) |
| | | .map(mapResponse(tClass)) |
| | | .map(mapResponse(context, tClass)) |
| | | .unsubscribeOn(Schedulers.newThread()) |
| | | .observeOn(AndroidSchedulers.mainThread()) |
| | | .subscribe(mySubscriber) |
| | | } |
| | | |
| | | private fun <T> mapResponse(tClass: Class<T>): Function<Any, BaseResponse<T>> { |
| | | private fun <T> mapResponse(context: Context, tClass: Class<T>): Function<Any, BaseResponse<T>> { |
| | | return Function { rawResponse -> |
| | | when (rawResponse) { |
| | | is BaseResponse<*> -> { |
| | |
| | | val response = BaseResponse<T>().apply { |
| | | code = temp.code |
| | | msg = temp.msg ?: "" |
| | | success = temp.success |
| | | } |
| | | |
| | | // 处理token失效的情况 |
| | | if (temp.code == NetConstans.TOKEN_INVALID) { |
| | | // 可以在这里添加重定向到登录页面的逻辑 |
| | | // redirectToLogin() |
| | | BusinessProvider.getBusinessProvider().startLoginNavigotor.navigateToLogin(context) |
| | | return@Function response |
| | | } |
| | | |
| | |
| | | } |
| | | is List<*> -> { |
| | | try { |
| | | @Suppress("UNCHECKED_CAST") |
| | | response.content = MyJsonParser.getListByJson( |
| | | MyJsonParser.getJsonbyList(content), |
| | | tClass |
| | | ) as T |
| | | // 直接处理List类型的content,不需要重新解析 |
| | | when { |
| | | // 如果目标类型是List的子类(如PaymentMethodListResponse),直接转换 |
| | | List::class.java.isAssignableFrom(tClass) -> { |
| | | @Suppress("UNCHECKED_CAST") |
| | | response.content = content as T |
| | | } |
| | | // 如果content是Map列表,尝试转换为目标对象列表 |
| | | content.isNotEmpty() && content[0] is Map<*, *> -> { |
| | | val jsonData = MyJsonParser.getJsonbyList(content) |
| | | @Suppress("UNCHECKED_CAST") |
| | | response.content = MyJsonParser.getListByJson(jsonData, tClass) as T |
| | | } |
| | | else -> { |
| | | @Suppress("UNCHECKED_CAST") |
| | | response.content = content as T |
| | | } |
| | | } |
| | | } catch (e: Exception) { |
| | | Log.e(TAG, "Error parsing list content", e) |
| | | // 如果解析失败,尝试直接转换 |
| | | try { |
| | | @Suppress("UNCHECKED_CAST") |
| | | response.content = content as T |
| | | } catch (e2: Exception) { |
| | | Log.e(TAG, "Failed to cast content directly", e2) |
| | | } |
| | | } |
| | | } |
| | | is Int, is String, is Boolean -> { |