rxJava中的类型不匹配

时间:2019-06-06 11:52:48

标签: kotlin rx-java2

我试图重用放置在retryWhen运算符中的某些代码,但由于它表示我提供了错误的类型而无法编译。

以下代码包含一个运行良好的retryWhen运算符:

var startPos = 0
val startPositions = BehaviorSubject.createDefault(startPos)

startPositions.flatMap { startPos -> App.context.repository.getConnections(startPos) }
    .flatMap { connections ->
        App.context.repository.storeConnections(connections)
    }
    .doOnNext { connections ->
        run {
            if (connections.isNotEmpty()) {
                startPos += 40
                startPositions.onNext(startPos)
            }
        }
    }
    .retryWhen(ExpBackoff(DefaultJitter(), delay = 1, unit = TimeUnit.SECONDS, retries = 5)) // About 30 seconds max.
    .subscribeOn(Schedulers.io())
    .observeOn(AndroidSchedulers.mainThread())
    .subscribe(
        { connections ->
            if (connections.isEmpty()) {
                getConnectionsCompleted()
            }
        }
    )

这是我要重用retryWhen运算符的代码:

App.context.repository.getUserSettings()
    .subscribeOn(Schedulers.io())
    .retryWhen(ExpBackoff(DefaultJitter(), delay = 1, unit = TimeUnit.SECONDS, retries = 5)) // About 30 seconds max.
    .observeOn(AndroidSchedulers.mainThread())
    .subscribe(
        { userSettings ->
            App.context.repository.cachedUserSettings = userSettings

        }
    )

ExpBackoff类:

class ExpBackoff(
    private val jitter: Jitter,
    private val delay: Long,
    private val unit: TimeUnit,
    private val retries: Int = 0
) : io.reactivex.functions.Function<Observable<out Throwable>, Observable<Long>> {

    @Throws(Exception::class)
    override fun apply(observable: Observable<out Throwable>): Observable<Long> {
        return observable
            .zipWith(Observable.range(1, retries + 1), BiFunction<Throwable, Int, Int> { _, retryCount ->
                retryCount
            })
            .flatMap { attemptNumber ->
                if (attemptNumber == retries)
                    throw java.lang.Exception()
                else
                    Observable.timer(getNewInterval(attemptNumber), unit)
            }
    }

    private fun getNewInterval(retryCount: Int): Long {
        var newInterval = (delay * Math.pow(retryCount.toDouble(), 2.0) * jitter.get()).toLong()
        if (newInterval < 0) {
            newInterval = Long.MAX_VALUE
        }
        return newInterval
    }
}

api声明:

override fun getConnections(startPos: Int): Observable<List<Connection>> {
    return api.getConnections(startPos)
}

override fun getUserSettings(): Single<UserSettings> {
    return api.getSettings()
}

编译错误指示“类型不匹配”:

  

必填:功能!,出出版商<*>!>!

     

发现:ExpBackoff

在第二个示例中如何使retryWhen工作?

0 个答案:

没有答案