@@ -183,23 +183,6 @@ class DownloadService : LifecycleService() {
183183 }
184184 }
185185
186- /* *
187- * Initiate download [Job] using [DownloadItem] by creating file according to [FileType]
188- * for the requested file.
189- */
190- private fun start (item : DownloadItem ) {
191- item.path = when (item.type) {
192- FileType .AUDIO -> getDownloadPath(DownloadHelper .AUDIO_DIR , item.fileName)
193- FileType .VIDEO -> getDownloadPath(DownloadHelper .VIDEO_DIR , item.fileName)
194- FileType .SUBTITLE -> getDownloadPath(DownloadHelper .SUBTITLE_DIR , item.fileName)
195- }.apply { deleteIfExists() }.createFile()
196-
197- lifecycleScope.launch(coroutineContext) {
198- item.id = Database .downloadDao().insertDownloadItem(item).toInt()
199- downloadFile(item)
200- }
201- }
202-
203186 /* *
204187 * Download file and emit [DownloadStatus] to the collectors of [downloadFlow]
205188 * and notification.
@@ -378,17 +361,45 @@ class DownloadService : LifecycleService() {
378361 return response.body
379362 }
380363
364+ /* *
365+ * Returns true if the current amount of downloads is still less than the maximum amount of
366+ * concurrent downloads.
367+ */
368+ private fun mayStartNewDownload (): Boolean {
369+ val downloadCount = downloadQueue.valueIterator().asSequence().count { it }
370+ return downloadCount < DownloadHelper .getMaxConcurrentDownloads()
371+ }
372+
373+ /* *
374+ * Initiate download [Job] using [DownloadItem] by creating file according to [FileType]
375+ * for the requested file.
376+ */
377+ private fun start (item : DownloadItem ) {
378+ item.path = when (item.type) {
379+ FileType .AUDIO -> getDownloadPath(DownloadHelper .AUDIO_DIR , item.fileName)
380+ FileType .VIDEO -> getDownloadPath(DownloadHelper .VIDEO_DIR , item.fileName)
381+ FileType .SUBTITLE -> getDownloadPath(DownloadHelper .SUBTITLE_DIR , item.fileName)
382+ }.apply { deleteIfExists() }.createFile()
383+
384+ lifecycleScope.launch(coroutineContext) {
385+ item.id = Database .downloadDao().insertDownloadItem(item).toInt()
386+
387+ if (mayStartNewDownload()) {
388+ downloadFile(item)
389+ } else {
390+ pause(item.id)
391+ }
392+ }
393+ }
394+
381395 /* *
382396 * Resume download which may have been paused.
383397 */
384398 fun resume (id : Int ) {
385399 // If file is already downloading then avoid new download job.
386- if (downloadQueue[id]) {
387- return
388- }
400+ if (downloadQueue[id]) return
389401
390- val downloadCount = downloadQueue.valueIterator().asSequence().count { it }
391- if (downloadCount >= DownloadHelper .getMaxConcurrentDownloads()) {
402+ if (! mayStartNewDownload()) {
392403 toastFromMainThread(getString(R .string.concurrent_downloads_limit_reached))
393404 lifecycleScope.launch(coroutineContext) {
394405 _downloadFlow .emit(id to DownloadStatus .Paused )
0 commit comments