Seems like a noob question but can someone tell me...
# compose
a
Seems like a noob question but can someone tell me why it would be bad to pass an activity to a screen/top-level Composable (one that already takes a ViewModel for instance, so it’s not skippable)?
s
Why do your composables need to know about your activity? What are you trying to do?
a
For
calculateWindowSizeClass
but actually I’m just asking for knowledge. I know, for that, you can just calculate it and pass that down but I wanna know for doing a code review, what exactly is the reason.
s
Yes exactly, at the place you’d send an activity, simply calculate the WindowSizeClass there and send that instead. Personally I’d request this to be changed if I saw an Activity being passed into a composable. I can’t think of a reason why I’d ever do it atm. No reason for a composable to know about Android like that imo.
a
Personally I’d request this to be changed if I saw an Activity being passed into a composable
Right, and I agree, but with what reason?
s
You said it yourself I guess, it makes the function not skippable for one. But on top of that it makes it less reusable too. If you pass the
WindowSizeClass
instead there’s a much bigger chance you’re gonna have that available to you to call this composable from various other places.
f
I think the comments in documentation are pretty clear on the reason:
Copy code
setContent {
    // Calculate the window size class for the activity's current window. If the window
    // size changes, for example when the device is rotated, the value returned by
    // calculateSizeClass will also change.
    val windowSizeClass = calculateWindowSizeClass(this)
    // Perform logic on the window size class to decide whether to use a nav rail.
    val useNavRail = windowSizeClass.widthSizeClass > WindowWidthSizeClass.Compact

    // MyScreen knows nothing about window size classes, and performs logic based on a
    // Boolean flag.
    MyScreen(useNavRail = useNavRail)
}
Especially the last comment:
MyScreen knows nothing about window size classes, and performs logic based on a Boolean flag.
Your Composable does not have to have any dependency on Activity or any other class. You can just tell it how it should behave and not on what data it should behave. The resulting Composable will be more reusable and more maintainable.
a
I guess de-coupling is enough of a reason. Thanks!