Skip to content

Instantly share code, notes, and snippets.

@illuzor
Created September 22, 2018 20:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save illuzor/1f26f2fee5393e98c838c12532cf6763 to your computer and use it in GitHub Desktop.
Save illuzor/1f26f2fee5393e98c838c12532cf6763 to your computer and use it in GitHub Desktop.
package com.illuzor.lesson.wallpapers.model
import com.illuzor.lesson.wallpapers.api.api
import com.illuzor.lesson.wallpapers.extensions.runInBackground
import com.illuzor.lesson.wallpapers.extensions.runInMainThread
import okhttp3.ResponseBody
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import java.io.File
import java.io.FileOutputStream
class ViewModelWallpaper : ViewModelBase() {
private var file: File? = null
fun load(url: String, file: File) {
this.file = file
state = State.PROGRESS
api.downloadFile(url).enqueue(object : Callback<ResponseBody> {
override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) {
if (response.isSuccessful) {
runInBackground {
val inputStream = response.body()!!.byteStream()
inputStream.copyTo(FileOutputStream(file))
runInMainThread {
state = State.LOADED
loadListener()
}
}
} else {
state = State.ERROR
loadListener()
}
}
override fun onFailure(call: Call<ResponseBody>, t: Throwable) {
state = State.ERROR
loadListener()
}
})
}
override fun onCleared() {
if (state != State.LOADED && file != null && file!!.exists())
file!!.delete()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment