Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
fun onDownloadPodcastClicked(podcastId: Int, index: Int) {
if (downloadQueue.containsKey(podcastId)) return
val download: Flow<Int> = provideDownloadFlow(podcastId)
downloadQueue[podcastId] = download
observeDownload(index, download)
}
private fun provideDownloadFlow(podcastId: Int): Flow<Int> {
return flow {
var progress = 10
emit(progress)
repeat(100) {
progress += Random.nextInt(10, 25)
delay(500L)
if (progress >= 100) emit(100) else emit(progress)
if (progress >= 100) {
downloadQueue.remove(podcastId)
return@flow
}
}
}.flowOn(Dispatchers.Default)
}
private fun observeDownload(index: Int, downloadFlow: Flow<Int>) {
viewModelScope.launch(Dispatchers.Default) {
downloadFlow.collect { progress ->
val updatedPodcast = _podcasts.value[index].copy(downloadProgress = progress)
val mutablePodcasts = _podcasts.value.toMutableList()
mutablePodcasts[index] = updatedPodcast
_podcasts.value = mutablePodcasts.toList()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment