Skip to content

Instantly share code, notes, and snippets.

@Skyyo
Last active April 18, 2021 18:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Skyyo/c8c163fe132794689a770950d4eb15aa to your computer and use it in GitHub Desktop.
Save Skyyo/c8c163fe132794689a770950d4eb15aa to your computer and use it in GitHub Desktop.
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