D.Sanxhez
D.Sanxhez

Reputation: 137

Recover the response of my service in another class with retrofit2 in kotlin

I have a call to my service with retrofit in which I get an answer and I need to send it to another class.

I have tried to save the response data in a ContentValues ​​and send them by means of a function but this does not work.

fun dataEmployee(name: String, numEmp: String): ConsultMovResponse? {
    var cMov = PersonData(name, numEmp)
    var pos: ConsultMovResponse?
    RetrofitClient.instMov.consultMov(cMov).enqueue(object : Callback<ConsultMovResponse> {
        override fun onResponse(call: Call<ConsultMovResponse>, response: Response<ConsultMovResponse>) {
            pos = response?.body()
            //return response, this code does not work.
            return pos?

        }

        override fun onFailure(call: Call<ConsultMovResponse>, t: Throwable) {
            println("Error  : " + t.stackTrace.toString())
            println("Error  : " + t.message)
        }
    })
    return pos?
}

Upvotes: 0

Views: 697

Answers (1)

Fred
Fred

Reputation: 17095

The way you're using Retrofit, it'll execute the request asynchronously. This means that before it has a chance to finish the request, the function dataEmployee will return an uninitialised pos.

There are different ways to go about this, but an easy one is to propagate the callback. Say you define the function as:

fun dataEmployee(name: String, numEmp: String, callback: (ConsultMovResponse?) -> Unit)

The last argument is a function that should be called when onResponse is called. Something like:

override fun onResponse(call: Call<ConsultMovResponse>, response: Response<ConsultMovResponse>) {
    callback(response?.body())
}

The way you can call now the method would be:

dataEmployee("Foo", "1234") {
     // Use the implicit parameter `it` which will be the response
}

Edit For the error you can follow a similar process. Let's change dataEmployee to:

fun dataEmployee(name: String, numEmp: String, onSuccess (ConsultMovResponse?) -> Unit, onFailure: (Throwable) -> Unit) 

On failure you can then call:

override fun onFailure(call: Call<ConsultMovResponse>, throwable: Throwable) {
       onFailure(throwable)
}

Now you call dataEmployee like so:

dataEmployee("foo", "1234",
       onSuccess = { /*handle success*/ },
       onFailure = { /*`it` will be the error */ })

Upvotes: 1

Related Questions