dav1d337
dav1d337

Reputation: 15

How to pass Retrofit API call as a parameter?

I want to pass a Retrofit API Call as a parameter to a method. Here is my minified code:

interface API {
    @POST("/test")
    fun postTest(): Call<Response>
}
fun test() {
   post(client.postTest())
}


private lateinit var client: Api


private fun post(function: Call<Response>) {
 if (::client.isInitialized) {
   function.enqueue(object : Callback<Response> {
                override fun onResponse(
                    call: Call<Response>,
                    response: Response<Response>
                ) {
                    if (response.isSuccessful) {
                        // do something
                    } else {
                        // do something
                    }
             }

             override fun onFailure(call: Call<Response>, t: Throwable) {
                    // do something
            }
         })
   }
}

The APIClient is initiated correctly. My problem is that the API Call is executed before passed to the post()-function, which leads to unhandled errors if something went wrong.

Upvotes: 0

Views: 203

Answers (1)

Pawel
Pawel

Reputation: 17268

You can pass a method reference that will create your Call object lazily in your post function:

fun test() {
   post(client::postTest)
}

private fun post(lazyCall: () -> Call<Response>) {
   lazyCall().enqueue(object : Callback<Response> {
     //...
   })
}

Upvotes: 1

Related Questions