'Jetpack compose check if a function has been run in preview mode

Is this possible to check if a function has been run in preview mode in Jetpack compose? I have a function that returns a proper string to use in the app but this function uses some objects which disable preview mode for @Composable components. What I could do is to pass val isPreview: Boolean = false flag to every component and then run a simplified function if the flag is true but this adds some boilerplate code to every composable.



Solution 1:[1]

They don't (as of Jan 2022) host the @Preview Jetpack Compose code in a your MainActivity when Preview-ing items in Android Studio.

This means you can walk up the context.baseContext tree to determine if you're in your app's MainActivity class or another app's top-level activity class. My top-level activity is called MainActivity, so:

fun Context.findMainActivityOrNull(): MainActivity?{
  var context = this
  while (context is ContextWrapper) {
    if (context is MainActivity) return context
    context = context.baseContext
  }
  return null
}

This makes it so I can avoid setting the status bar color when in preview, that way it doesn't crash the preview trying to do that.

You call the above function like this:

context.findMainActivityOrNull() //when in a non-@Composable area

If you're in a @Composable function, then you should be able to go:

LocalContext.current.findMainActivityOrNull()

You can get fancy and wrap the misbehaving class up in an adapter to be neat and tidy about it, or just check if the result of the above is null when working around a few issues.

Solution 2:[2]

This will violate the functional paradigm of a composable function. It should be stateless and will not care if its running in preview mode or in an actual app or else, you will encounter unexpected bugs in the future when the app gets very large to manage.

You should try to refactor or restructure your composable so that it will only depend on the string directly as a parameter. The preview mode can send a hardcoded string for this composable but for your actual app, you can call that function that returns the proper string (which uses some objects).

More about "Thinking in Compose" here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Michael
Solution 2 crjacinro