Home > Net >  CountDownTimer in jetpack compose
CountDownTimer in jetpack compose

Time:08-25

I am experimenting with CountDownTimer in jetpack compose with the following code

@Composable
fun Timer() {
    val millisInFuture: Long = 10 * 1000 // TODO: get actual value

    val timeData = remember {
        mutableStateOf(millisInFuture)
    }

    val countDownTimer =
        object : CountDownTimer(millisInFuture, 1000) {
            override fun onTick(millisUntilFinished: Long) {
                Log.d("TAG", "onTick: ")
                timeData.value = millisInFuture
            }

            override fun onFinish() {
               
            }
        }
    
    DisposableEffect(key1 = "key") {
        countDownTimer.start()
        onDispose {
            countDownTimer.cancel()
        }
    }

    Text(
        text = timeData.value.toString()
    )
}

In the logcat I am able to see the timer is ticking but the UI is not updating . Please explain why there is on recomposition on changing the value of state variable.

CodePudding user response:

Well, Within the CountDownTimer, instead of setting millisInFuture, you should set millisUntilFinished. That variable holds the updated value, the millisInFuture never changes

timeData.value = millisUntilFinished

CodePudding user response:

Composable only recompose when there is state change either from the Composable function param or by the value change of State<T> inside the Composable itself like mutableStateOf() or mutableStateListOf(). In your case, you haven't start the countDownTimer itself. Try to call countDownTimer.start() inside the DisposableEffect. Second you set the timeData with the wrong value, try to set it with millisUntilFinished

  • Related