Hello guys I wonder if coding ui composables like ...
# compose-android
a
Hello guys I wonder if coding ui composables like that is ok or not ? Can you share your opinions ?
Copy code
@Composable
fun Screen() {
    val myCustomComposable = rememberMyCustomComposable()

    Column {
        myCustomComposable.View()
        Button(onClick = { myCustomComposable.increaseNumber() }) {
            Text(text = "Click Me")
        }
    }
}

@Stable
class MyCustomComposable {

    private val someInnerState = mutableIntStateOf(0)

    fun increaseNumber() {
        someInnerState.intValue++
    }

    fun  decreaseNumber() {
        someInnerState.intValue--
    }

    @Composable
    fun View() {
        Column {
            Text(text = "${someInnerState.intValue}")
        }
    }
}

@Composable
fun rememberMyCustomComposable() = remember {
    MyCustomComposable()
}
e
Why do you need that rememberMyCustomComposable?
z
Please keep longer code snippets to the thread.
It’s more conventional to call the function itself the “composable”, not an object or class
What you’ve got is a state holder class plus a composable function. The google best practice is to generally prefer composables as top-level functions that take state holder objects, but functionally there’s no difference between that and what you’re doing.
I probably wouldn’t ship that as public API for a library, but for your own internal code it’s probably fine. It could get messy though for larger state holders where you might want to pass fakes to the composable for testing.
a
@electrolobzik for that particular example its not necessary but if you accept any parameter from Screen composable that it will be mandatory to keep MyComposable object between recompositions. I think your question was about that particular sample but anyway 🙂
@Zach Klippenstein (he/him) [MOD] thank you. Why i ended up with a code like that is because i wanted to use StateHolders but at somepoint my composable needed an internal state so that was not possible to keep that in the StateHolder so i should keep that with composable it self so at that point i tought maybe i can move the composable under the StateHolder class etc
Im agree that this is not suitable for public apis
t
I would recommend to use a top level function for the composable and create a stateholder class and remember that stateholder class and provide it as parameter to the composeable function.
a
Thank you for your responses that was helpful 👍
z
you can always make your private properties internal if you only need to prevent access from other modules, we do that a lot in compose itself
a
Yes for other modules its ok. In that case the composable were in same module so that was why i tried to find a different way. At the end of the day all can be solved with different archutectural decisions. So composition over inheritance wins 😄