I want to start timer as soon as activity start bu...
# compose
n
I want to start timer as soon as activity start but it keep on starting again and again attached video also for reference and code
c
@Napa Ram can you edit your post to put the code in this thread please? https://kotlinlang.slack.com/archives/CJLTWPH7S/p1616265877303000
👍 1
n
Copy code
class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            CountDownAppWithComposeTheme {
                // A surface container using the 'background' color from the theme
                Surface(color = MaterialTheme.colors.background) {
                    CountDown()
                }
            }
        }
    }
}

@Composable
fun CountDown() {

    var nums: String by remember{ mutableStateOf("")}
    var setView: String by remember{ mutableStateOf("00:00")}

    val countNum = object: CountDownTimer(140000, 1000){
        override fun onTick(millisUntilFinished: Long) {
//            nums = millisUntilFinished/1000
            val minutes = TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished)

            // long seconds = (milliseconds / 1000);
            val seconds = TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished)
            val tt = TimeUnit.MINUTES.toSeconds(minutes)

            nums = String.format(Locale.ENGLISH,"%02d  : %02d",minutes,seconds-tt)
            setView = nums
        }

        override fun onFinish() {
            setView = "Finished"
        }
    }.start()


    Column(modifier = Modifier.padding(16.dp), verticalArrangement = Arrangement.Center) {
        Text(text = setView, modifier = Modifier.padding(bottom = 8.dp),
        style = MaterialTheme.typography.h5)
        Button(onClick = { countNum.start() }) {
            Text(text = "Start CountDown")
            
        }

    }
}
u
Try to remember your
countNum
n
@uli you mean something like that
Copy code
var countNum1 : CountDownTimer by remember {mutableStateOf()}
u
Copy code
val countNum = remember { 
    object: CountDownTimer(140000, 1000){
...
    }.start()
}
No state here. Just a
val
that should be remembered instead of being recreated on recomposition
And maybe you should start/stop the timer as
DisposableEffect
https://jorgecastillo.dev/jetpack-compose-effect-handlers
👍 2