如何在 OnResponse 函数之外使用 Retrofit 响应? [英] How can I use the Retrofit response outside the OnResponse function?
问题描述
我想获取改造响应列表并在 OnResponse 函数之外使用它,但是我尝试这样做时我总是得到一个空对象.这是我的源代码
I want to get the retrofit response list and use it outside the OnResponse function, but went I try to do it I'm always getting a null object. Here is my source code
ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);
Call<ActivitiesResponse> call = apiService.getUserActivities(id);
call.enqueue(new Callback<ActivitiesResponse>() {
// If success
@Override
public void onResponse(Call<ActivitiesResponse>call, Response<ActivitiesResponse> response) {
list = response.body().getActivities();// I'm getting a not null response
}
// If failed
@Override
public void onFailure(Call<ActivitiesResponse>call, Throwable t) {
// Log error here since request failed
Log.e(TAG, t.toString());
}
});
//When I try to use the list here I'm getting a null object
推荐答案
请求是异步的,因此当您尝试返回一个值时,该请求可能尚未完成,因此您无法在请求之外使用它.如果您想从请求中返回值,请使用回调接口.
Requests are async, so when you try to return a value, the request is likely not done yet so you cannot use it outside of the request. If you want to return values from the request use callback interfaces.
将代码更改为方法并传递回调参数
Change your code to a method and pass a callback parameter
示例
public void doRequest(final ApiCallback callback) {
ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);
Call<ActivitiesResponse> call = apiService.getUserActivities(id);
call.enqueue(new Callback<ActivitiesResponse>() {
// If success
@Override
public void onResponse(Call<ActivitiesResponse>call, Response<ActivitiesResponse> response) {
list = response.body().getActivities();
callback.onSuccess(list); // pass the list
}
// If failed
@Override
public void onFailure(Call<ActivitiesResponse>call, Throwable t) {
// Log error here since request failed
Log.e(TAG, t.toString());
}
});
}
public interface ApiCallback{
void onSuccess(ArrayList<YOURTYPE> result);
}
onResume() 中的用法示例,基本上你可以在任何你想要的地方执行此操作:
Example usage in onResume(), basically you can do this anywhere you want:
public void onResume(){
super.onResume();
doRequest(new ApiCallback(){
@Override
public void onSuccess(ArrayList<YOURTYPE> result){
//do stuff here with the list from the request
}
});
}
让我知道这是否符合您的需求
Let me know if this fits your needs
这篇关于如何在 OnResponse 函数之外使用 Retrofit 响应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!