首页 > 解决方案 > 无法覆盖应用功能

问题描述

我遇到了以下代码:

import io.reactivex.Observable
import io.reactivex.functions.BiFunction
import java.util.concurrent.TimeUnit

    class ExpBackoff(
      private val jitter: Jitter,
      private val delay: Long,
      private val unit: TimeUnit,
      private val retries: Int = 0
    ) : 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), BiFunction<Throwable, Int, Int> { _, retryCount ->
              retryCount
            })
            .flatMap { attemptNumber -> 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
      }
    }

位于:

https://leandrofavarin.com/exponential-backoff-rxjava-operator-with-jitter

此代码无法编译。这一行是错误的:

Function<Observable<out Throwable>, Observable<Long>>

函数只接受一个参数。我在这里真的很困惑。写这篇文章的人清楚地表明他写了这段代码,我认为它可以工作,或者至少在他写的时候可以工作。但我怀疑 Kotlin 改变了 Function 的接口。即使我删除了第二个参数,代码也不会编译,因为 apply 函数不能被覆盖,因为它不是 Function 接口的一部分。

我该如何解决这个问题?

标签: kotlin

解决方案


看起来您缺少正确的Function导入。以下代码适用于我的 IDE。

import io.reactivex.Observable
import io.reactivex.functions.BiFunction
import io.reactivex.functions.Function
import java.util.concurrent.TimeUnit

class ExpBackoff(
    private val jitter: Jitter,
    private val delay: Long,
    private val unit: TimeUnit,
    private val retries: Int = 0
) : 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), BiFunction<Throwable, Int, Int> { _, retryCount ->
                retryCount
            })
            .flatMap { attemptNumber -> 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
    }
}

推荐阅读