Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Manage condition logic in stateless compose in jetpack compose

I am learning State hosting in jetpack compose. I have created two separated function ContentStateful and ContentStateLess. In my ContentStateLess there is a lot of view inside them and I am checking some condition and change view accordingly. I am guessing that there is no condition/business logic inside Stateful compose. So what is the proper way of doing this kind of logic in here.

ContentStateful

@Composable
fun ContentStateful(
    viewModel: PairViewModel = getViewModel()
) {
    ContentStateLess(viewModel)
}

ContentStateLess

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

@Composable
fun ContentStateLess(
    viewModel: PairViewModel
) {
    Text()
    Text()
    Image()
    if (viewModel.isTrue) {
         Image()
         // more item here
    } else {
          Text()
         // more item here
    }
    Image()
}

So what is the best recommendation for this if - else logic in ContentStateLess(). Many Thanks

>Solution :

If you are building stateless Composables it’s better not to pass anything like ViewModel. You can pass Boolean parameter instead. When you wish to move your custom Composable to another screen or another project you will need to move ViewModel either.

The reason Google recommends stateless Composables is it’s difficult to test, you can easily test a Composable with inputs only.

Another thing you experience the more states inner composables have to more exposure you create for your composable being in a State that you might not anticipate.

When you build simple Composables with one, two, three layers might not be an issue but with more states and layers state management becomes a serious issue. And if you somehow forget or miss a state inside a Composable you might end up with a behavior that’s not expected. So to minimize risks and make your Composables testable you should aim to manage your states in one place and possible in a state holder class that wraps multiple states.

@Composable
fun ContentStateLess(
    firstOneTrue: Boolean
) {
    Text()
    Text()
    Image()
    if (firstOneTrue) {
         Image()
         // more item here
    } else {
          Text()
         // more item here
    }
    Image()
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading