summaryrefslogtreecommitdiffhomepage
path: root/android/src
diff options
context:
space:
mode:
Diffstat (limited to 'android/src')
-rw-r--r--android/src/main/kotlin/net/mullvad/mullvadvpn/util/SmartDeferred.kt32
1 files changed, 32 insertions, 0 deletions
diff --git a/android/src/main/kotlin/net/mullvad/mullvadvpn/util/SmartDeferred.kt b/android/src/main/kotlin/net/mullvad/mullvadvpn/util/SmartDeferred.kt
new file mode 100644
index 0000000000..a7732c08ef
--- /dev/null
+++ b/android/src/main/kotlin/net/mullvad/mullvadvpn/util/SmartDeferred.kt
@@ -0,0 +1,32 @@
+package net.mullvad.mullvadvpn.util
+
+import kotlinx.coroutines.launch
+import kotlinx.coroutines.Deferred
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.GlobalScope
+import kotlinx.coroutines.Job
+
+class SmartDeferred<T>(private val deferred: Deferred<T>) {
+ private val jobTracker = JobTracker()
+
+ private var active = true
+
+ fun awaitThen(action: T.() -> Unit): Long? {
+ if (active) {
+ return jobTracker.newJob(GlobalScope.launch(Dispatchers.Default) {
+ deferred.await().action()
+ })
+ } else {
+ return null
+ }
+ }
+
+ fun cancelJob(jobId: Long) {
+ jobTracker.cancelJob(jobId)
+ }
+
+ fun cancel() {
+ active = false
+ jobTracker.cancelAllJobs()
+ }
+}