Last active
February 13, 2018 22:20
-
-
Save paramsen/4e29f35bd58ad2b53bc0d63af3d2772e to your computer and use it in GitHub Desktop.
Rx/OkHttp Android file downloader
This file contains hidden or 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 java.io.File; | |
import io.reactivex.Single; | |
import io.reactivex.schedulers.Schedulers; | |
import okhttp3.OkHttpClient; | |
import okhttp3.Request; | |
import okhttp3.Response; | |
import okio.BufferedSink; | |
import okio.BufferedSource; | |
import okio.Okio; | |
/** | |
* Simple file downloader using OkHttp, Okio and RxJava2 | |
* | |
* build.gradle dependencies: | |
* compile 'io.reactivex.rxjava2:rxandroid:2.0.1' | |
* compile 'io.reactivex.rxjava2:rxjava:2.0.1' | |
* compile 'com.squareup.okhttp3:okhttp:3.7.0' | |
* | |
* @author Pär Amsen 04/2017 | |
*/ | |
public class OkHttpFileDownloader { | |
private OkHttpClient client = new OkHttpClient(); | |
public Single<File> download(String url, File out) { | |
return Single.<File>create(subscriber -> { | |
Request request = new Request.Builder() | |
.url(url) | |
.build(); | |
Response response = client.newCall(request).execute(); | |
BufferedSource source = Okio.buffer(response.body().source()); | |
BufferedSink sink = Okio.buffer(Okio.sink(out)); | |
source.readAll(sink); | |
source.close(); | |
sink.close(); | |
subscriber.onSuccess(out); | |
}).subscribeOn(Schedulers.io()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
So basically the download never fails, right? 😂