I am trying to create a Queue manager for my Android app.
In my app, I show a list of videos in the RecyclerView. When the user clicks on any video, I download the video on the device. The download itself is working fine and I can even download multiple videos concurrently and show download progress for each download.
The Issue: I want to download only 3 videos concurrently and put all the other download in the queue.
Here is my Retrofit service generator class:
object RetrofitInstance {
private val downloadRetrofit by lazy {
val dispatcher = Dispatcher()
dispatcher.maxRequestsPerHost = 1
dispatcher.maxRequests = 3
val client = OkHttpClient
.Builder()
.dispatcher(dispatcher)
.build()
Retrofit.Builder()
.baseUrl(BASE_URL)
.client(client)
.addConverterFactory(GsonConverterFactory.create())
.build()
}
val downloadApi: Endpoints by lazy {
downloadRetrofit.create(Endpoints::class.java)
}
}
And here is my endpoint interface class:
interface Endpoints {
@GET
@Streaming
suspend fun downloadFile(@Url fileURL: String): Response<ResponseBody>
}
And I am using Kotlin coroutine to start the download:
suspend fun startDownload(url: String, filePath: String) {
val downloadService = RetrofitInstance.downloadApi.downloadFile(url)
if (downloadService.isSuccessful) {
saveFile(downloadService.body(), filePath)
} else {
// callback for error
}
}
I also tried reducing the number of threads Retrofit could use by using Dispatcher(Executors.newFixedThreadPool(1))
but that didn't help as well. It still downloads all the files concurrently.
Any help would be appreciated. Thanks!
EDIT
Forgot to mention one thing. I am using a custom view for the recyclerView item. These custom views are managing their own downloading state by directly calling the Download class.