Kotlin协程+Retrofit下载文件并实现进度监听

协程+Retrofit:Kotlin实现文件下载及进度监听与WorkManager集成
本文介绍了如何使用Kotlin协程与Retrofit配合下载文件,并通过监听实现下载进度更新,同时展示了如何将此功能与WorkManager结合,以后台下载提高用户体验。

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:
评论 8
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

TieJun~

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值