summaryrefslogtreecommitdiffhomepage
path: root/ui/src/main/java/com/wireguard/android/util/Extensions.kt
diff options
context:
space:
mode:
authorHarsh Shandilya <me@msfjarvis.dev>2020-09-16 15:30:15 +0530
committerJason A. Donenfeld <Jason@zx2c4.com>2020-09-16 18:01:06 +0200
commit2f088938c6c8c718d0a4ed639c18868257e354a1 (patch)
tree236d0b8c5695dc4c327079290e2d732e5852fc33 /ui/src/main/java/com/wireguard/android/util/Extensions.kt
parent53adb0e9a60c4a614179a916668a1a02264d1848 (diff)
ui: replace GlobalScope with a hand-rolled CoroutineScope
GlobalScope has numerous problems[1] that make it unfit for use in most applications and making it behave correctly requires an excessive amount of verbosity that's alleviated simply by using any other scope. Since we run multiple operations in the context of the application's lifecycle, introduce a new scope that is created when our application is, and cancelled upon its termination. While at it, make the scope default to Dispatchers.IO to reduce pressure on the UI event loop. Tasks requiring access to the UI thread appropriately switch context making the change completely safe. 1: https://medium.com/@elizarov/the-reason-to-avoid-globalscope-835337445abc Signed-off-by: Harsh Shandilya <me@msfjarvis.dev>
Diffstat (limited to 'ui/src/main/java/com/wireguard/android/util/Extensions.kt')
-rw-r--r--ui/src/main/java/com/wireguard/android/util/Extensions.kt4
1 files changed, 4 insertions, 0 deletions
diff --git a/ui/src/main/java/com/wireguard/android/util/Extensions.kt b/ui/src/main/java/com/wireguard/android/util/Extensions.kt
index c8892295..22ef8bd7 100644
--- a/ui/src/main/java/com/wireguard/android/util/Extensions.kt
+++ b/ui/src/main/java/com/wireguard/android/util/Extensions.kt
@@ -11,6 +11,7 @@ import androidx.annotation.AttrRes
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import androidx.preference.Preference
+import com.wireguard.android.Application
import com.wireguard.android.activity.SettingsActivity
import kotlinx.coroutines.CoroutineScope
@@ -24,6 +25,9 @@ fun Fragment.requireTargetFragment(): Fragment {
return requireNotNull(targetFragment) { "A target fragment should always be set for $this" }
}
+val Any.applicationScope: CoroutineScope
+ get() = Application.getCoroutineScope()
+
val Preference.activity: SettingsActivity
get() = context as? SettingsActivity ?: throw IllegalStateException("Failed to resolve SettingsActivity")