通常,当我从okhttp3回复得到回复时,代码成功并且我使用Response主体处理ui。这通常涉及将行放在runOnUIThread()
或new Handler(Looper.getMainLooper()).post(...)
内。为了节省标签,这有时会创建并将传输层代码分成单独的回调,我可以这样做吗?
public abstract class AbsCustomCallback implements okhtt3.Callback {
@Override
public abstract void onFailure(Call call, IOException e);
@Override
public void onResponse(Call call, final Response response) throws IOException {
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
try {
if (response.isSuccessful()) {
onSuccessMainThread(response);
} else {
onFailureCodeMainThread(response);
}
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
public abstract void onSuccessMainThread(Response response) throws IOException;
public abstract void onFailureCodeMainThread(Response response) throws IOException;
}
此实施是否始终有效?这将强制新的CustomCallback实现onFailure,onSuccessMainThread和onFailureCode回调方法。