本文接上一篇博文:OkHttp初探:如何使用OkHttp進行Get或Post請求?Kotlin版本,
文章目錄
- 通用模塊封裝
- 下載檔案,帶進度,一般封裝
- 使用flow封裝
通用模塊封裝
這里封裝一寫通用的代碼,先知道一下就可以了,
/**
* 日志列印
*/
fun log(vararg msg: Any?) {
val nowTime = SimpleDateFormat("HH:mm:ss:SSS").format(System.currentTimeMillis())
println("$nowTime [${Thread.currentThread().name}] ${msg.joinToString(" ")}")
}
/**
* 進度通用回呼 不使用flow封裝的話 使用這個
*/
internal typealias ProgressBlock = (state: DownloadState) -> Unit
/**
* 下載狀態機
*/
sealed class DownloadState {
/**
* 未開始
*/
object UnStart : DownloadState()
/**
* 下載中
*/
class Progress(var totalNum: Long, var current: Long) : DownloadState()
/**
* 下載完成
*/
class Complete(val file: File?) : DownloadState()
/**
* 下載失敗
*/
class Failure(val e: Throwable?) : DownloadState()
/**
* 下載失敗
*/
class FileExistsNoDownload(val file: File?) : DownloadState()
}
下載檔案,帶進度,一般封裝
fun downloadFile(url: String, destFileDirName: String, progressBlock: ProgressBlock) {
//下載狀態 默認未開始
var state: DownloadState = DownloadState.UnStart
progressBlock(state)
// TODO: 2021/12/27 file 創建與判斷可以封裝
/**
* file 創建判斷 可以封裝
*/
val file = File(destFileDirName)
val parentFile = file.parentFile
if (!parentFile.exists()) {
parentFile.mkdirs()
}
if (file.exists()) {
//檔案存在 不需要下載
state = DownloadState.FileExistsNoDownload(file)
progressBlock(state)
return
} else {
file.createNewFile()
}
//下載
val okHttpClient = OkHttpClient()
val request = Request.Builder().url(url).build()
okHttpClient.newCall(request).enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
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封裝呢?
所以,下面基于Flow的封裝就來了,直接切換到Main執行緒,美滋滋,
知識儲備:
Kotlin:Flow 全面詳細指南,附帶原始碼決議,
Flow : callbackFlow使用心得,避免踩坑!
/**
* 使用Flow改造檔案下載
* callbackFlow 可以保證執行緒的安全 底層是channel
*/
fun downloadFileUseFlow(url: String, destFileDirName: String) = callbackFlow<DownloadState> {
var state: DownloadState = DownloadState.UnStart
send(state)
//獲取檔案物件
val file = File(destFileDirName).also { file ->
val parentFile = file.parentFile
if (!parentFile.exists()) {
parentFile.mkdirs()
}
if (file.exists()) {
state = DownloadState.FileExistsNoDownload(file)
send(state)
//流關閉,回傳
close()
return@callbackFlow
} else {
file.createNewFile()
}
}
//下載
val okHttpClient = OkHttpClient().newBuilder()
.dispatcher(dispatcher)
.writeTimeout(30, TimeUnit.MINUTES)
.readTimeout(30, TimeUnit.MINUTES)
.build()
val request = Request.Builder()
.url(url)
.build()
okHttpClient.newCall(request).enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
//更新狀態
state = DownloadState.Failure(e)
this@callbackFlow.trySendBlocking(state)
close()
}
override fun onResponse(call: Call, response: Response) {
//下載
val body = response.body
if (response.isSuccessful && body != null) {
//完整長度
val totalNum: Long = body.contentLength()
//當前下載的長度
var currentProgress: Long = 0L
var len = 0
response.use {
//等效于 FileOutputStream(file) 輸出流
val outputStream = file.outputStream()
//輸入流
val byteStream = body.byteStream()
try {
val bates = ByteArray(2048)
//設定狀態物件拉出來,避免回圈一直創建物件
state = DownloadState.Progress(totalNum, currentProgress)
//回圈讀寫
do {
if (len != 0) {
currentProgress += len
outputStream.write(bates)
}
//更新進度
(state as DownloadState.Progress).current = currentProgress
this@callbackFlow.trySendBlocking(state)
len = byteStream.read(bates, 0, bates.size)
} while (len != -1)
//下載完成
state = DownloadState.Complete(file)
this@callbackFlow.trySendBlocking(state)
} catch (e: Exception) {
state = DownloadState.Failure(e)
this@callbackFlow.trySendBlocking(state)
} finally {
outputStream.close()
byteStream.close()
//關閉callbackFlow
this@callbackFlow.close()
}
}
} else {
//更新狀態且關閉
state = DownloadState.Failure(Exception(response.message))
this@callbackFlow.trySendBlocking(state)
close()
}
}
})
//使用channelFlow 必須使用awaitClose 掛起flow等待channel結束
awaitClose {
log("callbackFlow關閉 .")
}
}
.buffer(Channel.CONFLATED) //設定 立即使用最新值 buffer里面會呼叫到fuse函式,繼而呼叫到create函式重新創建channelFlow
.flowOn(Dispatchers.Default) //直接設定callbackFlow執行在異步執行緒
.catch { e ->
//例外捕獲重新發射
emit(DownloadState.Failure(e))
}
使用
//這里使用runBlocking只是為了跑程式,一般和lifecycleScope等合作使用
runBlocking(Dispatchers.Main) {
downloadFileUseFlow(
"https://dldir1.qq.com/weixin/Windows/WeChatSetup.exe",
"download/WeChatSetup.exe"
).onEach { downloadState ->
when (downloadState) {
is DownloadState.Complete -> log("下載完成 檔案路徑為 ${downloadState.file?.absoluteFile}")
is DownloadState.Failure -> log("下載失敗 ${downloadState.e?.message}")
is DownloadState.FileExistsNoDownload -> log("已經存在 ${downloadState.file?.absoluteFile}")
is DownloadState.Progress -> log("下載中 ${(downloadState.current.toFloat() / downloadState.totalNum) * 100}%")
DownloadState.UnStart -> log("下載未開始")
}
}.launchIn(this)
.join()
}
以上就是博主提供的兩種簡單的封裝方式了,
后面會陸續推出OkHttp高階使用,以及OkHttp原始碼分析博客,覺得不錯關注博主哈~😎
創作不易,如有幫助一鍵三連咯🙆?♀?,歡迎技術探頭噢!
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/401686.html
標籤:其他
上一篇:2021作業總結, 展望2022
