问题描述
我正在使用Android Annotation
进行样板操作,并使用Retrofit进行Api调用,在通过改造执行发帖请求时,我发现了一些问题:
I am using Android Annotation
for boilerplate, and Retrofit for Api calls, While doing post requests through retrofit I discovered a Some problems:
当我使用Retrofit调用对"GET"请求的异步调用时,我需要在调用完成后立即执行一些操作,并且由于我使用的是"Bean"注释,因此我无法使用"onResponse()"
When i am calling asynchronous call to "GET" request using Retrofit, I need to do some operation just after my call gets finished, and I can't use "onResponse()" because I am using "Bean" annotation
这没有道理吧?看一下代码
It doesn't make sense right? have a look on code
Bean类示例:
@EBean
public class someClass{
/* Suppose api is getting RestClient reference from Retrofit*/
@AfterInject
void doSomeWork(){ api = SampleAPI.Factory.getIstance(mcontext);}
/**
* Get list of all courses from database
* @Return List<CourseInfo> courseInfo objects
*/
public List<CourseInfo> GetCoursesList() {
final List<CourseInfo> cor = new ArrayList<>();
api.getAllCourses(user.getApikey()).enqueue(new Callback<List<CourseInfo>>() {
@Override
public void onResponse(retrofit2.Call<List<CourseInfo>> call, Response<List<CourseInfo>> response) {
Collections.copy(cor,response.body());
}
@Override
public void onFailure(retrofit2.Call<List<CourseInfo>> call, Throwable t) {
UiHelpers.showToast(mcontext,"Unable to get List of Course Names");
}
});
return cor;
}
}
调用Activity之类的东西
Calling in Activity something Like:
@EActivity(R.layout.something)
public class student extends AppCompatActivity {
@Bean
someClass some;
@AfterViews
void setInits(){
course = cc.GetCoursesList();
Toast.makeText(this,"Why this is running before getting all courses??",Toast.LENGTH_LONG).show();
}
}
我想知道如何使用Otto改善这种结构? v以及为什么我的这种结构失败了?
因为我无法从服务器获取coursesList!
I want to know how can I improve this structure using Otto? vAnd why my this structure is failing?
Because I am unable to get coursesList from server!!
推荐答案
因为这就是异步代码的工作方式?
Because that's how asynchronous code works?
改装不是阻止呼叫.
如果您想从UI线程上的onResponse执行操作,甚至不需要EventBus库,只需将回调作为方法的参数即可.
If you want to perform an action from onResponse back on the UI thread, you don't even need an EventBus library, just give the callback as the parameter of the method.
public void GetCoursesList(Callback<List<CourseInfo>> callback) {
api.getAllCourses(user.getApikey()).enqueue(callback);
}
该方法现在无效,因为再次进行了Retrofit不会阻止,因此在服务器请求发生时您返回了一个空列表
The method is now void because, again, Retrofit doesn't block, so you returned an empty list while the server request occurred
@AfterViews
void setInits(){
cc.GetCoursesList(new Callback<List<CourseInfo>>() {
// TODO: Implement the interface
} );
Toast.makeText(this,"Why this is running before getting all courses??",Toast.LENGTH_LONG).show();
}
这篇关于改造+奥托+ AA,如何简单地获取请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!