Skip to content

Instantly share code, notes, and snippets.

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)
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)
private fun downloadWithFlow(dummy: DummyData) {
CoroutineScope(Dispatchers.IO).launch {
ktor.downloadFile(dummy.file, dummy.url).collect {
when (it) {
is DownloadResult.Success -> {
}
is DownloadResult.Error -> {
}
@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)
sealed class DownloadResult {
object Success : DownloadResult()
data class Error(val message: String, val cause: Exception? = null) : DownloadResult()
data class Progress(val progress: Int): DownloadResult()
}
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
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)
startKoin {
androidContext(this@MyApplication)
modules(module {
single { initKtorClient() }
})
}
@francescogatto
francescogatto / Extensions.kt
Last active October 15, 2019 17:04
extensions init ktor #kkd
fun initKtorClient() = HttpClient(Android) {
install(Logging) {
logger = Logger.ANDROID
level = LogLevel.ALL
}
}
@francescogatto
francescogatto / build.gradle
Created October 15, 2019 17:01
build.gradle ktor #kkd
packagingOptions {
exclude 'META-INF/*.kotlin_module'
}
kotlinOptions {
jvmTarget = "1.8"
}