OkHttp初探2:如何使用OkHttp进行下载封装?带进度条?Kotlin+Flow版本。

本文介绍了如何使用Kotlin和Flow对OkHttp进行封装,实现文件下载并同步更新进度条。通过callbackFlow确保线程安全,详细展示了下载流程及异常处理,提供了一个全面的下载解决方案。
摘要由CSDN通过智能技术生成

state = DownloadState.Failure(e)

progressBlock(state)

}

override fun onResponse(call: Call, response: Response) {

response.use { res ->

//完整长度

var totalLength = 0L

//写入字节

val bytes = ByteArray(2048)

val fileOutputStream = FileOutputStream(file)

res.body?.also { responseBody ->

totalLength = responseBody.contentLength()

}?.byteStream()?.let { inputStream ->

try {

var currentProgress = 0L

var len = 0

state = DownloadState.Progress(totalLength, currentProgress)

do {

if (len != 0) {

currentProgress += len

fileOutputStream.write(bytes)

}

//状态改变

(state as DownloadState.Progress).current = currentProgress

progressBlock(state)

len = inputStream.read(bytes, 0, bytes.size)

} while (len != -1)

//状态改变完成

state = DownloadState.Complete(file)

progressBlock(state)

} catch (e: Exception) {

state = DownloadState.Failure(e)

progressBlock(state)

} finally {

inputStream.close()

fileOutputStream.close()

}

}

}

}

})

}

使用

downloadFile(

“https://dldir1.qq.com/weixin/Windows/WeChatSetup.exe”,

“download/WeChatSetup.exe”

) { state: DownloadState ->

when (val s = state) {

is DownloadState.Complete -> log(“下载完成 文件路径为 ${s.file?.absoluteFile}”)

is DownloadState.Failure -> log(“下载失败 ${s.e?.message}”)

is DownloadState.FileExistsNoDownload -> log(“已经存在 ${s.file?.absoluteFile}”)

is DownloadState.Progress -> log(“下载中 ${(s.current.toFloat() / s.totalNum) * 100}%”)

DownloadState.UnStart -> log(“下载未开始”)

}

}

使用flow封装


对于上述封装使用起来没有问题,但是如果在android上面要把进度显示出来的话,就需要手动切换到UI线程了。不太方便。既然都用kotlin了,那么为什么不解除协程Flow

  • 17
    点赞
  • 28
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值