在有延迟的加载某项事物时,利用回调往往能起到很好的展现代码清晰度的作用,比如网络的获取:
首先定义一个网络请求类:
public class CreateRoomRequest extends BaseRequest {
private GetService request;
public static class CreateRoomParam {
public String userId;
public String userAvatar;
public String userName;
public String liveTitle;
public String liveCover;
}
public CreateRoomRequest(){
request=request_start();
}
public void createRoom(CreateRoomParam parm){
Call<RoomInfo> call = request.getRoomInfo("create",parm.userId,parm.userName,parm.userAvatar,parm.liveCover,parm.liveTitle);
//发送网络请求(异步)
call.enqueue(new Callback<RoomInfo>() {
//请求成功时回调
@Override
public void onResponse(Call<RoomInfo> call, Response<RoomInfo> response) {
l.onSuccess(response.body());
}
//请求失败时回调
@Override
public void onFailure(Call<RoomInfo> call, Throwable throwable) {
l.onFail();
}
});
}
//设置监听器
public interface OnResultListener<T> {
void onFail();
void onSuccess(T t);
}
private OnResultListener l;
public void setOnResultListener(OnResultListener listener){
l=listener;
}
}
可以看出,可以在此类中定义一个接口,和它的set方法,让其他需要此网络请求的类实现此类中的接口,网络请求完成时调用OnResponse方法,而详细的接口中的方法在其他类中实现,这就很好的减少了类之间的代码的耦合度