Don't forget to drop continuation
This commit is contained in:
1 parent
c39e8eb43c
commit
d06cd5cc2d
1 file changed
+6
-1
@@ -10,15 +10,20 @@ import androidx.activity.result.contract.ActivityResultContracts
|
|||||||
import androidx.activity.result.contract.ActivityResultContracts.PickVisualMedia.VisualMediaType
|
import androidx.activity.result.contract.ActivityResultContracts.PickVisualMedia.VisualMediaType
|
||||||
import androidx.core.content.ContextCompat
|
import androidx.core.content.ContextCompat
|
||||||
import arrow.atomic.Atomic
|
import arrow.atomic.Atomic
|
||||||
|
import arrow.atomic.update
|
||||||
import kotlinx.coroutines.suspendCancellableCoroutine
|
import kotlinx.coroutines.suspendCancellableCoroutine
|
||||||
import kotlin.coroutines.resume
|
import kotlin.coroutines.resume
|
||||||
|
|
||||||
// Fuck off the silly Android launcher and callback :)
|
// Fuck off the silly Android launcher and callback :)
|
||||||
|
|
||||||
private typealias LauncherAndCallback<K, V> = Atomic<Pair<ActivityResultLauncher<K>, (V) -> Unit>>
|
private typealias LauncherAndCallback<K, V> = Atomic<Pair<ActivityResultLauncher<K>, (V) -> Unit>>
|
||||||
|
private fun <K, V> LauncherAndCallback<K, V>.cleanup() = update { it.copy {} }
|
||||||
private lateinit var requestPermission: LauncherAndCallback<String, Boolean>
|
private lateinit var requestPermission: LauncherAndCallback<String, Boolean>
|
||||||
private lateinit var pickVisualMedia: LauncherAndCallback<PickVisualMediaRequest, Uri?>
|
private lateinit var pickVisualMedia: LauncherAndCallback<PickVisualMediaRequest, Uri?>
|
||||||
private suspend fun <K, V> LauncherAndCallback<K, V>.await(key: K) = suspendCancellableCoroutine { cont -> updateAndGet { prev -> prev.copy { cont.resume(it) } }.first.launch(key) }
|
private suspend fun <K, V> LauncherAndCallback<K, V>.await(key: K) = suspendCancellableCoroutine { cont ->
|
||||||
|
updateAndGet { prev -> prev.copy { cont.resume(it) } }.first.launch(key)
|
||||||
|
cont.invokeOnCancellation { cleanup() } // Drop continuation when cancelled
|
||||||
|
}.apply { cleanup() } // Drop continuation when completed
|
||||||
|
|
||||||
fun ComponentActivity.initLauncher() {
|
fun ComponentActivity.initLauncher() {
|
||||||
requestPermission = Atomic(registerForActivityResult(ActivityResultContracts.RequestPermission()) { requestPermission.get().second(it) } to {})
|
requestPermission = Atomic(registerForActivityResult(ActivityResultContracts.RequestPermission()) { requestPermission.get().second(it) } to {})
|
||||||
|
|||||||
Reference in new issue
Block a user