Skip to content

Commit 082cc56

Browse files
feat: Use lifecycle-aware CoroutineScope in MyDownloadService
Refactored `MyDownloadService` to use a single, lifecycle-aware `CoroutineScope` backed by a `SupervisorJob`. This change prevents orphaned downloads and potential memory leaks by ensuring that all download coroutines are cancelled when the service is destroyed. The `downloadJob` is now cancelled in `onDestroy()`.
1 parent 83a17ba commit 082cc56

File tree

1 file changed

+6
-1
lines changed

1 file changed

+6
-1
lines changed

app/src/main/java/org/ole/planet/myplanet/datamanager/MyDownloadService.kt

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ import java.io.IOException
2424
import kotlin.math.roundToInt
2525
import kotlinx.coroutines.CoroutineScope
2626
import kotlinx.coroutines.Dispatchers
27+
import kotlinx.coroutines.SupervisorJob
2728
import kotlinx.coroutines.launch
2829
import okhttp3.ResponseBody
2930
import org.ole.planet.myplanet.MainApplication.Companion.createLog
@@ -50,6 +51,9 @@ class MyDownloadService : Service() {
5051
private var totalDownloadsCount = 0
5152
private var completedDownloadsCount = 0
5253

54+
private val downloadJob = SupervisorJob()
55+
private val downloadScope = CoroutineScope(downloadJob + Dispatchers.IO)
56+
5357
override fun onBind(intent: Intent?): IBinder? = null
5458

5559
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
@@ -75,7 +79,7 @@ class MyDownloadService : Service() {
7579

7680
updateNotificationForBatchDownload()
7781

78-
CoroutineScope(Dispatchers.IO).launch {
82+
downloadScope.launch {
7983
urls.forEachIndexed { index, url ->
8084
currentIndex = index
8185
initDownload(url, fromSync)
@@ -343,6 +347,7 @@ class MyDownloadService : Service() {
343347
stopForeground(true)
344348
} catch (_: Exception) {
345349
}
350+
downloadJob.cancel()
346351
notificationManager?.cancel(ONGOING_NOTIFICATION_ID)
347352
super.onDestroy()
348353
}

0 commit comments

Comments
 (0)