Slider in Android Jetpack Compose

Solution for Slider in Android Jetpack Compose
is Given Below:

  • Hi there
    I used jetpack compose to create a program that randomly generates a range of numbers.
    And returns them to a text-view. I
    also used a slider to set this range, but when I change the slider,
    the numbers change constantly, as if stuck in a loop. What is the
    reason for this problem? And what should I do?
    thanks

Here is my RandomGenerator Class ->

class RandomGenerator (
    
            private val stringSource: String,
            private val outputLength: Long = 4,
            private val startFrom: Int,
            private val to: Int) {
    
        @RequiresApi(Build.VERSION_CODES.N)
        fun generate(): String  {
    
            return Random()
                    .ints(outputLength, startFrom, to)
                    .asSequence()
                    .map(stringSource::get)
                    .joinToString("")
        }
    }

Here is my Slider that returns Int

@Composable
fun slider() : Int
{
    var sliderPosition by remember { mutableStateOf(1f) }

    Slider(
            modifier = Modifier.padding(10.dp).size(180.dp),

            value = sliderPosition,
            valueRange = 1f..10f,
            onValueChange = {sliderPosition = it}
    )

    return sliderPosition.roundToInt()
}

And …

 setContent {

        var msg by rememberSaveable { mutableStateOf("") }

        Column(modifier = Modifier
            .fillMaxSize()
            .padding(10.dp)) {

            val len = slider()

            val result = RandomGenerator(numbers, 10, 0, len).generate()

            msg = resutl

            Text(text = msg)

        }
    }

Oh the problem is that you are assigning a value to the ‘msg’ which is a state-holder, because of which a recomposition is triggered. It is an infinite loop.