在我的Android应用程序中,当我从后端读取段落时,我想实现成功和错误回调。在iOS中,它看起来像这样:
在我的Passage.h中:
-(void)getPassagesWithSuccessCallback:(void (^)(NSArray<Passage *> *))success errorCallback:(void (^)(NSString *))errorString;
在我的Passage.m中:
-(void)getPassagesWithSuccessCallback:(void (^)(NSArray<Passage *> *))success errorCallback:(void (^)(NSString *))errorString {
MyApiInterface* api = [MyApiInterface sharedInstance];
[api sendGetRequestTo:@"passages" successCallback:[Passage modelListCallback:success] errorCallback:error];
}
在我的Android应用中,我正在使用Volley
来处理我的API请求,但我希望通过使用带有public static void
方法的Passage.java类来进一步封装此API接口。通道。像这样:
public static void getPassagesForFirebaseUser(FirebaseUser user, Context context) {
final String url = URL_BASE + "/passages.json" + "?auth=" + user.getToken(false);
final JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
// convert JSON into ArrayList<Passage> object
// pass on this array of Passages in the success completion listener of the method that called this
// just like iOS does success(passages)
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// convert error to string
// pass on this errorString in the error completion listener of the method that called this
// just like iOS does error(errorString)
}
});
Volley.newRequestQueue(context).add(request);
}
有没有办法获得这种实施流程?
答案 0 :(得分:8)
您可以使用界面
public interface ICallbacks {
public void onResponse(JSONObject response);
public void onError(VolleyError error);
}
然后在你的例程代码中放入一个新的Callbacks实例(取决于你工作的ide可以自动生成方法)
public static void getPassagesForFirebaseUser(FirebaseUser user,
Context context, ICallbacks events) {
//here code and call ICallbacks methods
if(result){ events.onResponse(response); }
if(error){ events.onError(err); }
}
最终你可以用以下方法调用方法:
getPassagesForFirebaseUser(user, context, new ICallbacks(){
@Override
public void onResponse(JSONObject response){
//Success !!!
}
@Override
public void onError(VolleyError response){
//Error !!!
}
});
对不起我的英文,希望这个帮助!