Created
April 17, 2019 22:23
-
-
Save raxityo/f10f754c848262d4e9ca85e6f088c6c6 to your computer and use it in GitHub Desktop.
Retrofit extensions to save file to Disk.
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 android.content.Context | |
import io.reactivex.Observable | |
import okhttp3.ResponseBody | |
import okio.Okio | |
import retrofit2.Response | |
import java.io.File | |
private val <T> Response<T>.attachmentFileName | |
get() = headers()["Content-Disposition"] | |
?.removePrefix("attachment; filename=") | |
fun Observable<Response<ResponseBody>>.saveToDisk(context: Context, fileName: String? = null): | |
Observable<File?> { | |
return map { response -> | |
val body = response.body() ?: return@map null | |
val attachmentFileName = fileName ?: response.attachmentFileName ?: return@map null | |
val destinationFile = File("${context.filesDir.path}/$attachmentFileName") | |
val bufferedSink = Okio.buffer(Okio.sink(destinationFile)) | |
bufferedSink.writeAll(body.source()) | |
bufferedSink.close() | |
destinationFile | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Sample usage: