gpt4 book ai didi

android - 如何为 for 循环中的每个项目执行异步任务?

转载 作者:行者123 更新时间:2023-12-02 12:44:52 24 4
gpt4 key购买 nike

我有一个可变列表中的 url 列表,我想执行 IO 操作,cacheVideo在每个网址上依次一个接一个

suspend fun cacheVideo(mediaItem: MediaItem) = {
val videoUrl = mediaItem.mediaUrl
val uri = Uri.parse(videoUrl)
val dataSpec = DataSpec(uri)

val progressListener =
CacheUtil.ProgressListener { requestLength, bytesCached, newBytesCached ->

val downloadPercentage: Double = (bytesCached * 100.0
/ requestLength)

if (downloadPercentage == 100.0) {
// I WANT TO RETURN HERE
}
}

try {
CacheUtil.cache(
dataSpec,
cache,
DataSourceFactory?.createDataSource(),
progressListener,
null
);
} catch (err: Exception) {
// IF ERROR, THEN RETURN NULL
}
}
我将如何塑造 cacheVideo使用协程来做到这一点?
uiScope.launch {
for(item in mediaItems){
cacheVideo(item) // I WANT TO WAIT HERE BEFORE GOING TO NEXT ITEM
}
}

最佳答案

您可以使用 suspendCancellableCoroutine 等待进度:

suspend fun cacheVideo(mediaItem: MediaItem) = suspendCancellableCoroutine { continuation ->
val videoUrl = mediaItem.mediaUrl
val uri = Uri.parse(videoUrl)
val dataSpec = DataSpec(uri)

val progressListener =
CacheUtil.ProgressListener { requestLength, bytesCached, newBytesCached ->

val downloadPercentage: Double = (bytesCached * 100.0
/ requestLength)

if (downloadPercentage == 100.0) {
continuation.resume() // resumes the execution of the corresponding coroutine
}
}

// continuation.invokeOnCancellation {
// // clear some resources, cancel tasks, close streams etc if need.
// }

try {
CacheUtil.cache(
dataSpec,
cache,
DataSourceFactory?.createDataSource(),
progressListener,
null
);
} catch (err: Exception) {
continuation.resume() // resumes the execution of the corresponding coroutine
}
}

关于android - 如何为 for 循环中的每个项目执行异步任务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62831144/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com