首页 > 解决方案 > 为什么我不能从改造中返回我的响应列表作为返回类型,而是我需要从活动中获得一个回调侦听器,然后传递数据

问题描述

这是我的休息控制器方法

有趣的 getPosts() : ArrayList {

    val result = ArrayList<Post>()

    val retrofit = RetrofitClient.retrofitInstance
    val service = retrofit?.create(ApiService::class.java)
    val call = service?.getPosts()

    call?.enqueue(object : Callback<List<Post>> {
        override fun onFailure(call: Call<List<Post>>, t: Throwable) {

        }

        override fun onResponse(call: Call<List<Post>>, response: Response<List<Post>>) {

            println(response.body()?.size)
            if(response.isSuccessful && response.body()!= null) {

                val posts = response.body()
                listener.onRestDataReceived(posts!!)
                    result.addAll(posts!!)

            }
        }

    })
    return result
}

当我尝试从返回类型访问数据时,我得到空数组列表,但是如果我使用接口回调方法并通过接口传递数据并在我的活动中实现接口,我可以访问数据

标签: androidrestkotlinretrofit2

解决方案


The enqueue(Callback<T> callback) method your are calling is asynchronous, so the actual result of enqueue(Callback<T> callback) you get in callback methods. In your getPosts() method after calling call?.enqueue your code execution immediately passes to return result; statement and that's why your are getting an empty array.


推荐阅读