Kotlin协程+Retrofit下载文件并实现进度监听
文章目录
1.前言
网上很多Retrofit+RxJava下载文件的功能,这里我使用kotlin+协程的方式使用一下,并且结合workmanager使用下载
DownloadWorker.startDownload(
this@MainActivity,
"https://dldir1.qq.com/wework/work_weixin/wxwork_android_3.0.31.13637_100001.apk",
this@MainActivity.cacheDir.path,
"wxwork_android_3.apk"
)
2. 实现过程
1. 构建下载的ApiService
import okhttp3.ResponseBody
import retrofit2.http.GET
import retrofit2.http.Streaming
import retrofit2.http.Url
interface ApiService {
@Streaming
@GET
suspend fun downloadFile(@Url fileUrl: String?): ResponseBody
}
2. 声明相关监听方法
typealias download_error = suspend (Throwable) -> Unit
typealias download_process = suspend (downloadedSize: Long, length: Long, progress: Float) -> Unit
typealias download_success = suspend (uri: File) -> Unit
3. 构建Retrofit,并且获取ApiService
import retrofit2.Retrofit
object HttpKit {
val retrofit = Retrofit.Builder()
.baseUrl("http://www.xxx.com")
.validateEagerly(true) //在开始的时候直接开始检测所有的方法
.build()
val apiService = retrofit.create(ApiService::class.java)
}
4. 定义返回实体
/**
* @author stj
* @Date 2021/10/28-16:42
* @Email 375105540@qq.com
*/
class HttpResult<out T> constructor(val value: Any?) {
val isSuccess: Boolean get() = value !is Failure && value !is Progress
val isFailure: Boolean get() = value is Failure
val isLoading : Boolean get() = value is Progress
fun exceptionOrNull(): Throwable? =
when (value) {
is Failure -> value.exception
else -> null
}
/*
.....代码省略
*/
companion object {
fun <T> success(value: T): HttpResult<T> =
HttpResult(value)
fun <T> failure(exception: Throwable): HttpResult<T> =
HttpResult(createFailure(exception))
fun <T> progress(currentLength: Long, length: Long, process: Float):HttpResult<T> =
HttpResult(createLoading(currentLength, length, process))
}
data class Failure(val exception: Throwable)
data class Progress(val currentLength: Long, val length:

本文介绍了如何使用Kotlin协程与Retrofit配合下载文件,并通过监听实现下载进度更新,同时展示了如何将此功能与WorkManager结合,以后台下载提高用户体验。
最低0.47元/天 解锁文章
5184





