【问题标题】:How to return error value and retry with timer如何返回错误值并使用计时器重试
【发布时间】:2020-03-04 13:34:21
【问题描述】:

我正在发出网络请求,当出现互联网离线等错误时,它应该向用户显示错误,但在后台重试,以便当用户访问互联网时它会自动获取数据。

我有以下代码,重试后返回错误,但我需要立即返回错误,但不知道该怎么做。有人可以帮忙吗?提前致谢。

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 ?: "")
    }

【问题讨论】:

  • 你应该考虑为互联网连接错误实现一个广播接收器,如果你有兴趣告诉我,我会尽力为你提供一些代码。
  • 我知道它可以用广播接收器完成,但我想用单流干净的方式完成。

标签: android kotlin retrofit rx-java2


【解决方案1】:

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

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

apiService.getForecastWeatherByLocation(...)
    .map { ... }
    .subscribeOn(...)
    .observeOn(...)
    .startWith(...)
    .onErrorReturn {
        retryObservable.subscribe()
        Resource.error(...)
    }
    .subscribe()

【讨论】:

    猜你喜欢
    • 2017-04-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-11
    • 2014-05-19
    • 2021-07-20
    • 2018-05-16
    相关资源
    最近更新 更多