Home » Android » Android Kotlin how to pass named function as parameter into another function to be executed when JsonObjectRequest return success?-Exceptionshub

Android Kotlin how to pass named function as parameter into another function to be executed when JsonObjectRequest return success?-Exceptionshub

Posted by: admin February 26, 2020 Leave a comment

Questions:

I have a function named doReq it will do a JsonObjectRequest and when success i need it to execute a named function i pass in with the success response return from the request. Please take a look at code below,

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 ->
            }
    )
}

Additional note, doReq will be called in other packages and each package has it’s own reqSuccess function. Ok below is correct now,

    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)
How to&Answers:

You should add lambda parameter to doReq() function:

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 ->
            }
    )
}

You can call that function like following:

doReq("someurl")