将函数作为参数传递并执行自定义函数?

时间:2019-06-18 11:17:08

标签: android kotlin kotlin-coroutines

在我的android应用中:

  suspend fun getTraidersList(): TransportResponse = withContext(Dispatchers.IO) {
            // some common methods
            try {
                val response: Response<List<Trader>> = traderMonitorRestClient.getTraidersList()
             //  some common methods
            } catch (e: Throwable) {
               // some comon methods
            }
        }

        suspend fun executeTraderOperation(traderOperation: Trader.Operation, base: String, quote: String): TransportResponse = withContext(Dispatchers.IO) {
            // some common methods
            try {
               val response: Response<Void> = traderMonitorRestClient.executeTraderOperation(traderOperation.toString().toLowerCase(), base.trim(), quote.trim(), sender, key)
             //  some common methods
            } catch (e: Throwable) {
               // some comon methods
            }
}

如您所见,我有2种方法,其中有许多常用方法。我想在单独的方法中提取此常用方法。 我想将函数作为参数传递给my_common_method。 可以在Kotlin中这样做吗?

suspend fun my_common_method(fun some_custom_function) {
            // some common methods
            try {
                val response: Response<*> = some_custom_function()
             //  some common methods
            } catch (e: Throwable) {
               // some comon methods
            }
        }

也许有更好的解决方案?

getTraidersList()中,功能some_custom_functiongetTraidersList()。在executeTraderOperation中,函数some_custom_functionexecuteTraderOperation。 在科特林有可能吗?

1 个答案:

答案 0 :(得分:2)

您可以做的是使用高阶函数:

suspend fun my_common_method(block: suspend () -> Response<TransportResponse>) {
            // some common methods
            try {
                val response = block()
             //  some common methods
            } catch (e: Throwable) {
               // some comon methods
            }
        }

然后您只需致电my_common_method {getTraidersList() }