Platform independent image picking
This commit is contained in:
@@ -0,0 +1,36 @@
|
||||
package app.klottr.images
|
||||
|
||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
import androidx.activity.result.PickVisualMediaRequest
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import app.klottr.net.ImageHandle
|
||||
|
||||
@Composable
|
||||
actual fun rememberVisualMediaPicker(): VisualMediaPicker {
|
||||
// Holds the in-flight callback across recompositions.
|
||||
val callbackState = remember { mutableStateOf<((ImageHandle?) -> Unit)?>(null) }
|
||||
|
||||
val launcher = rememberLauncherForActivityResult(
|
||||
contract = ActivityResultContracts.PickVisualMedia()
|
||||
) { uri ->
|
||||
val cb = callbackState.value
|
||||
callbackState.value = null
|
||||
cb?.invoke(uri?.let { ImageHandle.UriString(it.toString()) })
|
||||
}
|
||||
|
||||
return remember {
|
||||
object : VisualMediaPicker {
|
||||
override fun pickImage(onResult: (ImageHandle?) -> Unit) {
|
||||
// Prevent overlapping requests. Ignore if one is already active.
|
||||
if (callbackState.value != null) return
|
||||
callbackState.value = onResult
|
||||
launcher.launch(
|
||||
PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user