Skip to content

Instantly share code, notes, and snippets.

@rayworks
Created April 13, 2018 09:49
Show Gist options
  • Save rayworks/cfe50e56ed7e8d0be78c3c125346c20e to your computer and use it in GitHub Desktop.
Save rayworks/cfe50e56ed7e8d0be78c3c125346c20e to your computer and use it in GitHub Desktop.
A simple cancellable downloader
import okhttp3.ResponseBody;
import retrofit2.Call;
public interface Repository {
Call<ResponseBody> download(String url);
}
public void cancelCurrentDownloadingTask() {
if (call != null) {
call.cancel();
}
}
public Observable<ResponseBody> loadUrlResource(String url) {
return Observable.create(
subscriber -> {
call = repository.download(url);
// keep the local record of 'call' since the actual instance will be replaced.
final Call<ResponseBody> downloadCall = call;
try {
Response<ResponseBody> response = downloadCall.execute();
if (response.isSuccessful()) {
ResponseBody body = response.body();
subscriber.onNext(body);
subscriber.onCompleted();
} else {
subscriber.onError(
new Throwable("Http response error code:" + response.code()));
}
} catch (IOException e) {
e.printStackTrace();
if (downloadCall.isCanceled()) {
String message =
String.format(
Locale.ENGLISH, ">>> Cancelled request for %s", url);
subscriber.onError(new CancelledException(message));
} else {
subscriber.onError(e);
}
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment