有没有更好,更简单的方法来优化Kotlin中的帮助程序回调和处理程序代码?

时间:2018-11-29 01:12:28

标签: android kotlin android-handler

我正在使用带有重试逻辑的帮助程序类,该类在整个应用程序中都使用。我想知道是否有一种方法可以将处理程序和回调类组合为一个类,而不是将2个不同的类分别用于回调和一个处理程序。这是我的代码,如下所示: 重试器:

abstract class RetryHandler(private val totalRetries: Int = 0, private val delayMillis : Long = 0) : Handler() {

    private var retryCount: Int = 0

    fun retry(): Boolean {
        return if (retryCount++ < totalRetries) {
            if (delayMillis > 0) {
                postDelayed({ onRetry(retryCount) }, delayMillis)
            } else {
                onRetry(retryCount)
                true
            }
        } else false
    }

    abstract fun onRetry(retryCount: Int)
}

重试回调:

abstract class RetryableCallback(totalRetries: Int = 0, delayMillis : Long = 0)
    : RetryHandler(totalRetries, delayMillis), MyCallback {

    override fun handleTransactionCompleted() {
        if (!onCompleted()) {
            if (!retry()) {
                onFailed(null)
            }
        }
    }

    override fun handleTransactionFailed(e: MyException?) {
        if (!retry()) {
            onFailed(e)
        }
    }

    abstract fun onCompleted(): Boolean

    abstract fun onFailed(e: MyException? = null)
}

这是我在代码中使用它们的方式:

   private val newCallback = object: RetryableCallback(5, 5000) {
            override fun onRetry(retryCount: Int) {
    ....}
    override fun onCompleted(): Boolean {
    }
    }

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

好吧,只要我不完全了解目的,就这样说吧:

abstract class RetriableCallbackHandler(private val totalRetries: Int = 0, private val delayMillis : Long = 0) : Handler(), MyCallback {

    private var retryCount: Int = 0

    fun retry(): Boolean {
        return if (retryCount++ < totalRetries) {
            if (delayMillis > 0) {
                postDelayed({ onRetry(retryCount) }, delayMillis)
            } else {
                onRetry(retryCount)
                true
            }
        } else false
    }

    abstract fun onRetry(retryCount: Int)

    override fun handleTransactionCompleted() {
        if (!onCompleted()) {
            if (!retry()) {
                onFailed(null)
            }
        }
    }

    override fun handleTransactionFailed(e: MyException?) {
        if (!retry()) {
            onFailed(e)
        }
    }

    abstract fun onCompleted(): Boolean

    abstract fun onFailed(e: MyException? = null)
}