I have a straight forward button that I want to la...
# compose
c
I have a straight forward button that I want to launch an share intent. Right now I just wrote a fun in my composable file based off of this. It works fine. But I feel like maybe I shouldn't do this in my composable? I see three choices: 1️⃣ Should I bubble this event up to my nav host/activity to handle 2️⃣ Should I try to do this in my VM and have Hilt inject a context 3️⃣ Having it done like I do now "in the composable" is fine
1️⃣ 1
j
I definitely don’t know what the right answer is here, but when we did this in our app we landed on doing it in compose as the “right” thing to do. We mainly decided that way just to keep as much “Android Platform” specific code out of our ViewModel so we can unit test it without Roboelectric or some other tool. I guess I would lean towards options 1 or 3 with that in mind. Ultimately, I don’t see a compelling reason why any of the options would be outright wrong, though.
👍 1
f
I would not inject a
Context
in your VM to do this. I would suggest one of these approaches: • leave it in the composable as you have it now • create an injectable
LaunchManager
or similar that gets the application context injected and use that to launch the intent. Note that this would require the intent to have the flag New Task • define an interface that your activity implements to launch an intent, then cast the
LocalContext.current
to your interface and launch the intent
e
bubbling it up will allow you to register
Copy code
registerForActivityResult(StartActivityForResult()) { ... }
in an appropriate place in your app - you may not care about the result now, but you may need in the future
f
e
yes, although remember that like
registerForActivityResult
,
rememberLauncherForActivityResult
must be called statically on creation. registering it dynamically will not lead to correct results if your component is re-created
i
"called statically" just means "not within an if statement" for Compose; it isn't nearly as restrictive as the non-Compose world
e
calling it within a LazyColumn would also be problematic, wouldn't it?
i
If you have content keys defined on your items, even that should be fine - anywhere
rememberSaveable
would work,
rememberLauncherForActivityResult
will work
But should you be putting
rememberSaveable
in a LazyColumn item? Tbh, probably not very often - you'd usually hoist that that up