Skip to content

Instantly share code, notes, and snippets.

@petitviolet
Last active May 13, 2023 12:15
Show Gist options
  • Save petitviolet/b27b61972a6a18ca7b9e to your computer and use it in GitHub Desktop.
Save petitviolet/b27b61972a6a18ca7b9e to your computer and use it in GitHub Desktop.
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