Home > Blockchain >  Manage condition logic in stateless compose in jetpack compose
Manage condition logic in stateless compose in jetpack compose

Time:12-06

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

@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

CodePudding user response:

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()
}
  • Related