Last active
August 12, 2024 07:37
-
-
Save lsurvila/d3c034e5ee514009e31b to your computer and use it in GitHub Desktop.
Download file with Retrofit 2, OkHttp, Okio and RxJava
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 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); | |
} | |
}); | |
} |
Are you sure it's Retrofit 2? Package name is wrong in imports.
I am interested as well in progress listener!
What happens when the file is big??. I think with this approach will cause an OOM.
Any way to listen download progress? And can we show the download notification with this?
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
Is there a way to listener progress of downloading?