如何返回错误值并使用计时器重试

我正在发出网络请求,并且当出现诸如Internet脱机之类的错误时,它应该向用户显示一个错误,但会在后台重试,因此当用户访问Internet时,它会自动获取数据。

我有以下代码,重试后返回错误,但是我需要立即返回错误,但是没有任何线索。有人可以帮忙吗?预先感谢。

apiService.getForecastWeatherByLocation(latitude,longitude)
    .subscribeon(Schedulers.io()).observeon(Schedulers.io()).map { response ->
        if (response.isSuccessful) {
            Resource.success(
                transformForecastResponseToForecast(response.body())
            )
        } else {
            Resource.error(response.code(),response.message())
        }
    }
    .startWith(Resource.loading(null))
    .retryWhen { errors: Flowable<Throwable> ->
        errors.zipWith(
            Flowable.range(1,3 + 1),BiFunction<Throwable,Int,Int> { error: Throwable,retryCount: Int ->
                if (retryCount > 3) {
                    throw error
                } else {
                    retryCount
                }
            }
        ).flatMap { retryCount: Int ->
            Flowable.timer(
                2.toDouble().pow(retryCount.toDouble()).toLong(),TimeUnit.SECONDS
            )
        }
    }.onErrorReturn {
        Resource.error(AppConstants.UNKNOWN_ERROR,it.localizedMessage ?: "")
    }
lyc5748056 回答:如何返回错误值并使用计时器重试

我不认为在单个流中实现您想要的目标是不可行的,因为一旦调用onError(),流就关闭了。解决方法如何?

val retryObservable = apiService.getForecastWeatherByLocation(...)
    .map { ... }
    .subscribeOn(...)
    .observeOn(...)
    .retryWhen(...)

apiService.getForecastWeatherByLocation(...)
    .map { ... }
    .subscribeOn(...)
    .observeOn(...)
    .startWith(...)
    .onErrorReturn {
        retryObservable.subscribe()
        Resource.error(...)
    }
    .subscribe()
本文链接:https://www.f2er.com/3141314.html

大家都在问