Created
April 13, 2018 09:49
-
-
Save rayworks/cfe50e56ed7e8d0be78c3c125346c20e to your computer and use it in GitHub Desktop.
A simple cancellable downloader
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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