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

salomonbrys

11/13/2020, 12:42 PM
Is there a way to detect preview mode?
p

pavi2410

11/13/2020, 12:46 PM
I don't think so, but you could do something like this
Copy code
val PreviewAmbient = ambientOf { false }

@Preview
@Composable
fun MainScreenPreview() {
  Providers(PreviewAmbient provides true) {
    MainScreen()
  }
}

@Composable
fun MainScreen() {
  val isInPreview = PreviewAmbient.current
  ...
}
s

salomonbrys

11/13/2020, 12:47 PM
That's what I currently do... But if I forget to provide the ambient in a preview, then I get "ViewModels creation is not supported in Preview" errors. So I'm looking for a more resilient way.
How about
Copy code
@Composable val isPreview: Boolean get() = ContextAmbient.current.applicationContext !is Application
?
j

Joost Klitsie

11/13/2020, 1:21 PM
I think the common way is to write your composables as to not have them rely on a system. So instead of:
Copy code
@Preview
@Composable
fun MainScreen() {
    val viewModel by viewModels()// or however kids these days get their viewmodel
}
Copy code
@Composable
fun MainScreen() {
    val viewModel by viewModels()
    MainScreen(viewModel.viewState.collectAsState()) // Or pass in separate arguments
}

@Preview
@Composable
fun MainScreen(viewState: ViewState) {
    // display things
}
This also makes your composables less platform specific
s

sindrenm

11/13/2020, 1:33 PM
I think you mixed up a couple of things in that last example?
@Preview
should probably be on the first composable, and its function name would need to be different. simple smile
12 Views