繁体   English   中英

当JsonObjectRequest返回成功时,Android Kotlin如何将命名函数作为参数传递给另一个要执行的函数?

[英]Android Kotlin how to pass named function as parameter into another function to be executed when JsonObjectRequest return success?

我有一个名为 doReq 的函数,它将执行一个 JsonObjectRequest,当成功时我需要它来执行一个命名函数,我通过请求返回的成功响应传入。 请看下面的代码,

package mypackage1
fun reqSuccess(resp: JSONObject) {    
}
package mypackage2
fun doReq(url: String, how do i pass in reqSuccess function here?) {                
    val req: JsonObjectRequest = object : JsonObjectRequest(Request.Method.POST, url, json,
            Response.Listener { response ->
                // need to perform reqSuccess here passing in response
            },
            Response.ErrorListener { error ->
            }
    )
}

附加说明,doReq 将在其他包中调用,并且每个包都有自己的 reqSuccess 函数。 好的,下面是正确的,

    package mypackage2
    fun doReq(url: String, onSuccess: (response: JSONObject) -> Unit) {
        val req: JsonObjectRequest = object : JsonObjectRequest(Request.Method.POST, url, json,
                Response.Listener { response ->
                   onSuccess(response)
                },
                Response.ErrorListener { error ->
                }
        )
    }
package mypackage1
fun reqSuccess(resp: JSONObject) {    
}

doReg("someurl",::reqSuccess)

您应该将 lambda 参数添加到doReq()函数:

fun doReq(url: String, onSuccess: (response: JSONObject) -> Unit = ::reqSuccess) {
    val req: JsonObjectRequest = object : JsonObjectRequest(Request.Method.POST, url, json,
            Response.Listener { response ->
               onSuccess(response)
            },
            Response.ErrorListener { error ->
            }
    )
}

您可以调用该函数,如下所示:

doReq("someurl")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM