https://kotlinlang.org logo
Title
d

David W

12/27/2021, 1:58 AM
Is there a way to detect if your composable is being rendered as a Preview? Akin to
isInEditMode()
from standard Android.
👀 1
o

olonho

12/27/2021, 8:17 AM
@alexey.tsvetkov wdyt?
s

seb

12/27/2021, 8:37 AM
o

olonho

12/27/2021, 11:09 AM
it's Android-only at the moment, but see no reason not to have it on other platforms as well
a

alexey.tsvetkov

12/27/2021, 2:28 PM
I wonder what’s your usecase? I don’t see a reason against it, but I have not thought anyone needs that before today 🙂 Also feel free to create an issue at https://github.com/JetBrains/compose-jb/issues
d

David W

12/27/2021, 3:37 PM
I am not saying it's a good use-case, but I have a view that is using my service locator as part of rendering, and I suspect (am not sure) that this is causing the previewer to fail since it'd require the rest of the application running to instantiate that.
This is for a hobby project so I'm playing looser with the rules than I would for a work application 🙂
(deleted some irrelevant info, I had to restart IntelliJ to get the Previewer working again)
Just confirmed via commenting out and back in that using my service locator while rendering causes previewing to fail. All it's doing is resolving to a boolean, so I'd like to, in Preview mode, hardcode the boolean rather than using the SL.
if (!modVariant.mod(SL.access).isEnabled(modVariant)) {
                SmolButton(
                    modifier = Modifier
                        .padding(top = 4.dp)
                        .align(Alignment.CenterHorizontally),
                    onClick = {
                        GlobalScope.launch { SL.access.enableModVariant(modVariant) }
                    }
                ) {
                    Text("Enable")
                }
            }
is the part that, when commented out, allows the Previewer to work.
a

Alexander Kurasov[JB]

12/28/2021, 6:27 PM
I think you can create a @Preview wrapper for your actual Composable and pass the parameter from there. It looks simple and much more explicit
2