Skip to content

Instantly share code, notes, and snippets.

@raxityo
Created April 17, 2019 22:23
Show Gist options
  • Save raxityo/f10f754c848262d4e9ca85e6f088c6c6 to your computer and use it in GitHub Desktop.
Save raxityo/f10f754c848262d4e9ca85e6f088c6c6 to your computer and use it in GitHub Desktop.
Retrofit extensions to save file to Disk.
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
}
}
@raxityo
Copy link
Author

raxityo commented Apr 17, 2019

Sample usage:

// API Interface:
interface UserApi {
    @GET(Routes.photoUrl)
    fun getPhoto(): Observable<Response<ResponseBody>>
}

// In your Activity:
userApi
    .getPhoto()
    .saveToDisk(context)
	.subscribe()

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