https://kotlinlang.org logo
#compose
Title
# compose
m

manueldidonna

04/30/2020, 9:43 PM
Which is the best way to start an activity from a composable function and receives a result?
a

Adam Powell

04/30/2020, 10:51 PM
Right now there isn't a turnkey version of this, but have a look at the new activity result androidx API here: https://developer.android.com/jetpack/androidx/releases/activity
👍 1
the plan is to have a direct compose API built on top of this
so feel free to beat us to it if you'd like 🙂 we're going to use the same pieces here
m

manueldidonna

05/01/2020, 2:07 AM
From the docs I get that the
ComponentActivity
exposes an
ActivityResultRegistry
that contains a list of callbacks to be invoked when onActivityResult is triggered. The callbacks can be registered from other classes and scoped to a lifecycle owner. There's already an ambient to retrieve the lifecycle owner associated with the current activity, maybe I can provide the registry as an ambient too.
Copy code
@Composable
private fun LaunchActivity(contract: OpenMultipleDocuments) {
    val lifecycleOwner = LifecycleOwnerAmbient.current
    val registry = ActivityResultRegistryAmbient.current
    
    onPreCommit(registry, lifecycleOwner) {
        val launcher = registry.register("OPEN_DATA", OpenMultipleDocuments()) { uriList ->
           // do something
        }     
        launcher.launch()
        onDispose { launcher.unregister() }
    }
}
Do you think something like that would work?
@Adam Powell Here is what I've done
Copy code
@Composable
fun LoadSaveDataScreen() {
    val lifecycleOwner = LifecycleOwnerAmbient.current
    val registry = ActivityResultRegistryAmbient.current
    val launchIntent = savedInstanceState { false }
    val launcher = remember(registry, lifecycleOwner) {
        registry.register(
            "OPEN_DATA",
            lifecycleOwner,
            ActivityResultContracts.OpenDocument(),
            ActivityResultCallback { uri -> Log.d("compose", "uri: $uri") }
        )
    }
    onDispose {
        launcher.unregister()
    }
    if (!launchIntent.value) {
        Surface(color = MaterialTheme.colors.background, modifier = Modifier.fillMaxSize()) {
            Button(
                modifier = Modifier.fillMaxSize().wrapContentSize(Alignment.Center),
                onClick = { launchIntent.value = true }
            ) {
                Text(text = "LOAD SAVEDATA")
            }
        }
    } else {
        launchIntent.value = false
        launcher(arrayOf("/"))
    }
}
2 Views