@@ -13,8 +13,13 @@ import androidx.work.WorkManager
1313import androidx.work.WorkerParameters
1414import dagger.assisted.Assisted
1515import dagger.assisted.AssistedInject
16+ import kotlinx.coroutines.CancellationException
1617import kotlinx.coroutines.Deferred
18+ import kotlinx.coroutines.GlobalScope
19+ import kotlinx.coroutines.SupervisorJob
1720import kotlinx.coroutines.async
21+ import kotlinx.coroutines.cancelAndJoin
22+ import kotlinx.coroutines.launch
1823import kotlinx.coroutines.supervisorScope
1924import org.session.libsession.database.StorageProtocol
2025import org.session.libsession.database.userAuth
@@ -102,7 +107,10 @@ class BackgroundPollWorker @AssistedInject constructor(
102107
103108 try {
104109 Log .v(TAG , " Performing background poll for ${requestTargets.joinToString { it.name }} ." )
105- supervisorScope {
110+ // The polling process is independent from the worker's lifecycle, once it's started
111+ // it can't be safely cancelled.
112+ // This is fixed on dev and we can discard the workaround.
113+ GlobalScope .async(SupervisorJob ()) {
106114 val tasks = mutableListOf<Deferred <* >>()
107115
108116 // DMs
@@ -115,6 +123,7 @@ class BackgroundPollWorker @AssistedInject constructor(
115123
116124 // FIXME: Using a job here seems like a bad idea...
117125 BatchMessageReceiveJob (params).executeAsync(" background" )
126+ Log .d(TAG , " Polling messages finished." )
118127 }
119128 }
120129
@@ -127,6 +136,7 @@ class BackgroundPollWorker @AssistedInject constructor(
127136 async {
128137 Log .d(TAG , " Polling legacy group ${key.substring(0 , 8 )} ..." )
129138 poller.poll(key)
139+ Log .d(TAG , " Polling legacy group finished." )
130140 }
131141 }
132142 }
@@ -142,6 +152,7 @@ class BackgroundPollWorker @AssistedInject constructor(
142152 .apply { hasStarted = true }
143153 .poll()
144154 .await()
155+ Log .d(TAG , " Polling Open group finished." )
145156 }
146157 }
147158 }
@@ -151,6 +162,7 @@ class BackgroundPollWorker @AssistedInject constructor(
151162 tasks + = async {
152163 Log .d(TAG , " Polling all groups." )
153164 groupPollerManager.pollAllGroupsOnce()
165+ Log .d(TAG , " Polling groups finished." )
154166 }
155167 }
156168
@@ -168,10 +180,14 @@ class BackgroundPollWorker @AssistedInject constructor(
168180 if (caughtException != null ) {
169181 throw caughtException
170182 }
171- }
183+ }.await()
172184
173185 return Result .success()
174- } catch (exception: Exception ) {
186+ } catch (c: CancellationException ) {
187+ Log .v(TAG , " Background poll cancelled" )
188+ throw c
189+ }
190+ catch (exception: Exception ) {
175191 Log .e(TAG , " Background poll failed due to error: ${exception.message} ." , exception)
176192 return Result .retry()
177193 }
0 commit comments