Skip to content

Instantly share code, notes, and snippets.

startKoin {
androidContext(this@MyApplication)
modules(module {
single { initKtorClient() }
})
}
suspend fun HttpClient.downloadFile(file: File, url: String, callback: suspend (boolean: Boolean) -> Unit) {
val call = call {
url(url)
method = HttpMethod.Get
}
if (!call.response.status.isSuccess()) {
callback(false)
}
call.response.content.copyAndClose(file.writeChannel())
return callback(true)
suspend fun HttpClient.downloadFile(file: File, url: String, callback: suspend (boolean: Boolean) -> Unit) {
val response = call {
url(url)
method = HttpMethod.Get
}.response
val data = ByteArray(response.contentLength()!!.toInt())
var offset = 0
do {
val currentRead = response.content.readAvailable(data, offset, data.size)
offset += currentRead
sealed class DownloadResult {
object Success : DownloadResult()
data class Error(val message: String, val cause: Exception? = null) : DownloadResult()
data class Progress(val progress: Int): DownloadResult()
}
@francescogatto
francescogatto / Extensions.kt
Last active November 14, 2022 04:05
#KKD
suspend fun HttpClient.downloadFile(file: File, url: String): Flow<DownloadResult> {
return flow {
val response = call {
url(url)
method = HttpMethod.Get
}.response
val data = ByteArray(response.contentLength()!!.toInt())
var offset = 0
do {
val currentRead = response.content.readAvailable(data, offset, data.size)
private fun downloadWithFlow(dummy: DummyData) {
CoroutineScope(Dispatchers.IO).launch {
ktor.downloadFile(dummy.file, dummy.url).collect {
when (it) {
is DownloadResult.Success -> {
}
is DownloadResult.Error -> {
}
private fun downloadWithFlow(dummy: DummyData) {
CoroutineScope(Dispatchers.IO).launch {
ktor.downloadFile(dummy.file, dummy.url).collect {
withContext(Dispatchers.Main) {
when (it) {
is DownloadResult.Success -> {
myAdapter.setDownloading(dummy, false)
}
is DownloadResult.Error -> {
myAdapter.setDownloading(dummy, false)
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val dummy = dummyes[position]
with(holder.itemView) {
title.text = dummy.title
downloadIcon.isVisible = !dummy.file.exists()
documentTypeIcon.isVisible = dummy.file.exists()
progressBarDocument.isVisible = dummy.isDownloading
textProgress.isVisible = dummy.isDownloading
setOnClickListener {
listener(dummy)