Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to observe multiple downloads by id ? #57

Open
tosam144 opened this issue Mar 10, 2025 · 1 comment
Open

How to observe multiple downloads by id ? #57

tosam144 opened this issue Mar 10, 2025 · 1 comment

Comments

@tosam144
Copy link

tosam144 commented Mar 10, 2025

Thank you for this great library!

I don't know how to observe many downloads by ID. This is what I tried to do within my AndroidViewModel:

viewModelScope.launch {
        val filesToDownload = loadDownloads()
        filesToDownload.forEach { doc ->
                         val id = ketch.download(...)
                         viewModelScope.launch {
                                    ketch.observeDownloadById(id)
                                            .flowOn(Dispatchers.IO)
                                            .collect { downloadModel -> 
                                                   // Process the downloaded file if status == SUCCESS
                                                   if (downloadModel.status == Status.SUCCESS) {
                                                          Timber.d(downloadModel.url)
                                                   }
                                           }
                         }
               }    
        }

Function loadDownloads() is a suspend function which must run in its own IO coroutine. However, this approach does not work because I get multiple calls to the observe (probably due to the nested coroutines). If I omit the inner coroutine, it won't work either. The issue is, I must process each download right after the file is successfully downloaded. How do I solve this issue? Thank you so much.

@khushpanchal
Copy link
Owner

you can write separate observe function

fun observeDownloads() {
list.forEach { // list of ids provided by ketch
viewModelScope.launch {
ketch.observeDownloadById(it).distinctUnitChanged().flowOn(Dispatchers.IO).collectLatest {
// here you can check when download is success.
}
}
}
}

another approach to observeAllDownloads at one place
fun observeAllDownloads() {
viewModelScope.launch {
ketch.observeAllDownloads().distinctUnitChanged().flowOn(Dispatchers.IO).collectLatest {
// here you will get complete downloads list, and you can do the pre processing
}
}

Also I will be publishing new version of ketch by this weekend, there I will be adding another method to observeDownloads by multiple Ids.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants