Hanbit the Developer

[Kotlin] Implementation Retrofit2 Callback Function 본문

Mobile/Android

[Kotlin] Implementation Retrofit2 Callback Function

hanbikan 2021. 10. 1. 00:51

It's simple. Just use some parameters as Unit type, and invoke them.

 

First, make your custom api calling function as below:

fun <T> enqueueApiCall(
            call: Call<T>,
            onResponse: (Response<T>)->Unit,
            onFailure: ()->Unit
        ){
            call.enqueue(object: Callback<T> {
                override fun onResponse(call: Call<T>, response: Response<T>) {
                    onResponse.innoke()
                }
                override fun onFailure(call: Call<T>, t: Throwable) {
                    onFailure.invoke()
                }
            })
        }

 

And call it in your actual code like:

val call = retrofit.create(YourApi::class.java)
// # Skipped initializing call

enqueueApiCall(
	call,
    {
    	Log.d("Test", "onResponse")
    },
    {
    	Log.d("Test", "onFailure")
    }
)