我正在尝试在我的应用程序中实现Clean Architecture。我的API在成功和失败的情况下发送响应:
{
"data": [],
"statusCode": 200,
"statusMessage": "success",
"success": true
}
OR
{
"statusCode": xxx,
"statusMessage": "Invalid Details",
"success": false
}
[在以前的方法中,我使用Retrofit和BaseResponse
POJO类来处理数据场景,但是在我当前的应用程序中,我使用带有RxJava和Retrofit的Clean Architecture。
我将获得Observable,Flowable或Single之一,但其类型为BaseResponse
。
data class BaseResponse<T>(
@SerializedName("status") val status: Boolean,
@SerializedName("statuscode") val statusCode: Int? = null,
@SerializedName("message") val message: String? = null,
@SerializedName("data") val data: T? = null
)
我正在使用自定义RESULT作为所有成功或失败的Rx来检查Domain中的Rx错误:
fun <T> Single<T>.toResult(): Single<Result<T>> = this
.map { Result.Success(it) as Result<T> }
.onErrorReturn {
Result.Failure(
if (it is CompositeException) it.exceptions.last().toView()
else it.toView()
)
}
但是为了处理动态响应,我无法将它们包装起来。
我尝试了How to wrap API responses to handle success and error based on Clean Architecture?和其他几个,但都没有解决。
如何在用例/存储库或数据层中包装项目
data class NetworkResponse<D, E>(
val data: List<D>?,
val statusCode: Int,
val statusMessage: String,
val success: Boolean,
val errors: List<E>?
)
// retrofit funcs
fun login(...): Single<NetworkResponse<LoginSuccessResponse, LoginErrorResponse>>
fun prices(...): Flowable<NetworkResponse<PriceSuccessResponse, PriceErrorResponse>>
现在,您不必处理自定义解串器和基本响应。