Skip to content

Instantly share code, notes, and snippets.

@paramsen
Last active February 13, 2018 22:20
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save paramsen/4e29f35bd58ad2b53bc0d63af3d2772e to your computer and use it in GitHub Desktop.
Save paramsen/4e29f35bd58ad2b53bc0d63af3d2772e to your computer and use it in GitHub Desktop.
Rx/OkHttp Android file downloader
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());
}
}
@mradzinski
Copy link

So basically the download never fails, right? 😂

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment