Last active
April 18, 2021 18:06
-
-
Save Skyyo/c8c163fe132794689a770950d4eb15aa to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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