When do I need to add @Composable with Android Studio Compose?

Issue

The following code is from the project.

I find that fun MainScreen() add @Composable, and fun launchDetailsActivity doesn’t add @Composable.

It make me confused. I think all function which apply to Compose should to add @Composable, why doesn’t fun launchDetailsActivity add @Composable?

@AndroidEntryPoint
class MainActivity : ComponentActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        ...
        setContent {
            ProvideWindowInsets {
                ProvideImageLoader {
                    CraneTheme {
                        MainScreen(
                            onExploreItemClicked  { launchDetailsActivity(context  this, item  it) }
                        )
                    }
                }
            }
        }
    }
}


@Composable
fun MainScreen(onExploreItemClicked: OnExploreItemClicked) {
  ...
}


fun launchDetailsActivity(context: Context, item: ExploreModel) {
    context.startActivity(createDetailsActivityIntent(context, item))
}

Solution

Function with @Composable is not just a function it tells the compose compiler that this is a UI element. Take this data and build a Widget with it.

So you have to determine when you will add @Composable based on whether this function draws something in the UI or not. In the non compose world you can think of this function like a View.

For example, this function takes a parameter name and builds a Text widget with the text “Hello $name” which you can see in the UI.

@Composable
fun Greeting(name: String) {
    Text("Hello $name")
}

But

fun getName(firstName: String, lastName: String): String {
    return "$firstName $lastName"
}

This function is not a composable function. It is not annotated with @Composable because it is not a widget, it shouldn’t render anything in the UI. It just takes two parameters, Concatenates them, and returns the String.

In your case, MainScreen is the function that is rendering the Main screen of your app so it is a UI element. But function launchDetailsActivity doesn’t draw anything in the UI. It just navigates from one activity to another activity.

Few things to remember:

Function with @Composable doesn’t return anything.

You can’t call a composable function from a non-composable function.

Unlike non-composable function composable function start with an Uppercase letter.

You can read this doc for details https://developer.android.com/jetpack/compose/mental-model

Answered By – Rafiul

Leave a Comment