Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
OkHttp Callback on Main Thread.
public abstract class MainThreadCallback implements Callback {
private static final String TAG = MainThreadCallback.class.getSimpleName();
abstract public void onFail(final Exception error);
abstract public void onSuccess(final String responseBody);
@Override
public void onFailure(final Request request, final IOException e) {
runOnUiThread(new Runnable() {
@Override
public void run() {
e.printStackTrace();
if (e.getMessage().contains("Canceled") || e.getMessage().contains("Socket closed")) {
ToastUtil.show(R.string.canceled);
} else {
onFail(e);
}
}
});
}
@Override
public void onResponse(final Response response) throws IOException {
if (!response.isSuccessful() || response.body() == null) {
onFailure(response.request(), new IOException("Failed"));
return;
}
runOnUiThread(new Runnable() {
@Override
public void run() {
try {
onSuccess(response.body().string());
} catch (IOException e) {
e.printStackTrace();
onFailure(response.request(), new IOException("Failed"));
}
}
});
}
private void runOnUiThread(Runnable task) {
new Handler(Looper.getMainLooper()).post(task);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.