如何在Option android中设置getOrElse函数的重复最大计数



我对返回错误的请求的最大重复次数有问题。在我的情况下,我需要向后端发送一个新的请求,如果之前的请求失败了,但最多3次。我使用选项来获得结果,返回数据或错误:

fun sendRequest(): Single<Option<BeResponse>

sendRequest()函数内部,我将其从Either<ApiError, Data>转换为BeResponse

data class BeReponse(
val error: ApiError? = null,
val data: Data? = null
)

当我试图获取数据时,如果之前的请求失败,我需要发送请求。所以我用的是:

sendRequest().flatMap{ option -> 
option.map {
if (option.error != null) {
Single.just(null.toOption())
} else {
Single.just(it)
}
}.getOrElse{ sendRequest() }
}

但如果我有错误,我会无限地调用sendRequest。如何设置它的最大尝试次数?

创建temp-var,然后在程序进行循环时增加它。。

查看此

var temp = 0
sendRequest().flatMap{ option -> 
option.map {
if (option.error != null) {
Single.just(null.toOption())
} else {
Single.just(it)
}
}.getOrElse{
if (temp < 3){
sendRequest()
temp = temp+1
} else{
//do your code to take action
}
}

最新更新