Reputation: 23
let's say I'm making a simple dnd dice roller (cause I am), I made it so it rolls a bunch of random numbers based on how many dice they want rolled and the type of dice. it then sends it to a text view one at a time(what I want); However, it only shows one number because it has no delay to let the the user see each number rolled (it only shows the last number).
How would I do that?
else if (numTimesRolled.progress <= 4) {
for (i in 0 until numTimesRolled.progress){
randNum = Random.nextInt(1, diceIsComfirm)
resultsArray[i] = randNum.toString()
}
for (i in 0 until numTimesRolled.progress){
randNumDisplay.text = resultsArray[i]
}
Upvotes: 0
Views: 239
Reputation: 93779
Non-coroutines solution is to post Runnables:
val delayPerNumber = 500L // 500ms
for (i in 0 until numTimesRolled.progress){
randNumDisplay.postDelayed({ randNumDisplay.text = resultsArray[i] }, i * delayPerNumber)
}
With a coroutine:
lifecycleScope.launch {
for (i in 0 until numTimesRolled.progress){
delay(500) // 500ms
randNumDisplay.text = resultsArray[i]
}
}
An advantage with the coroutine is it will automatically stop if the Activity or Fragment is destroyed, so if the Activity/Fragment is closed while the coroutine's still running, it won't hold your obsolete views in memory.
Upvotes: 1