实现自定义okhttp3.Callback

时间:2017-03-13 21:13:18

标签: java android multithreading okhttp3

通常,当我从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回调方法。

0 个答案:

没有答案