Skip to content

Instantly share code, notes, and snippets.

@lsurvila
Last active August 12, 2024 07:37
Show Gist options
  • Save lsurvila/d3c034e5ee514009e31b to your computer and use it in GitHub Desktop.
Save lsurvila/d3c034e5ee514009e31b to your computer and use it in GitHub Desktop.
Download file with Retrofit 2, OkHttp, Okio and RxJava
import com.squareup.okhttp.ResponseBody;
import okio.BufferedSink;
import okio.Okio;
import retrofit.Response;
import retrofit.http.GET;
import retrofit.http.Query;
import rx.Observable;
interface ApiService {
@GET("/media/download")
Observable<Response<ResponseBody>> download(@Query("id") String id);
}
public Observable<File> download(String id) {
return service.download(id)
.flatMap(this::saveFile);
}
public Observable<File> saveFile(Response<ResponseBody> response) {
return Observable.create((Observable.OnSubscribe<File>) subscriber -> {
try {
// you can access headers of response
String header = response.headers().get("Content-Disposition");
// this is specific case, it's up to you how you want to save your file
// if you are not downloading file from direct link, you might be lucky to obtain file name from header
String fileName = header.replace("attachment; filename=", "");
// will create file in global Music directory, can be any other directory, just don't forget to handle permissions
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC).getAbsoluteFile(), fileName);
BufferedSink sink = Okio.buffer(Okio.sink(file));
// you can access body of response
sink.writeAll(response.body().source());
sink.close();
subscriber.onNext(file);
subscriber.onCompleted();
} catch (IOException e) {
e.printStackTrace();
subscriber.onError(e);
}
});
}
@sergioborne
Copy link

What happens when the file is big??. I think with this approach will cause an OOM.

@Kazunka
Copy link

Kazunka commented Jul 6, 2018

Any way to listen download progress? And can we show the download notification with this?

@mochadwi
Copy link

mochadwi commented Jan 8, 2019

Up for listen download progress and download notification @lsurvila

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