android - 为什么我不能从改造中返回我的响应列表作为返回类型,而是我需要从活动中获得一个回调侦听器,然后传递数据
问题描述
这是我的休息控制器方法
有趣的 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
}
当我尝试从返回类型访问数据时,我得到空数组列表,但是如果我使用接口回调方法并通过接口传递数据并在我的活动中实现接口,我可以访问数据
解决方案
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.
推荐阅读
- python-3.x - 由于逗号,语法无效
- xml - 模板匹配和属性到节点
- javascript - 为什么我的 websocket php+javascript 代码不起作用?
- java - 将选择的日期时间对话框选择器转换为存储在 sqlite DB 中
- c++ - 错误:一元'*'的无效类型参数(有'int'):使用mergesort计算数组中的反转数
- java - 获取所有扩展类推断某些泛型的类
- mysql - MySQL 没有按预期使用索引
- jquery - 在hybris中动态生成标签文件
- python - Pandas 如何计算两个 DataFrame 之间的更新
- amazon-web-services - 我坚持连接 AWS Elastic Beanstalk 和 RDS