kotlinandroid-thread

Kotlin - delay between UI updates


I have created a simple tik-tac-toe game and have some bots you can play with. I am trying to have a delay between consecutive bot turns as otherwise all sequential bot moves appear on the screen at the same time

here is what I have tried in my code:

    // bot functionality
private fun botTurn(botDifficulty: Int) {
    var botMove = 100
    when (botDifficulty) {
        1 -> botMove = easyBot(confirmedMoves)
        2 -> botMove = mediumBot(activePlayer, confirmedMoves, maxPlayers)
        3 -> botMove = hardBot(activePlayer, confirmedMoves, maxPlayers)
        else -> Toast.makeText(this, "What sort of bot is this??", Toast.LENGTH_SHORT).show()
    }
    
    trueCellID = botMove
    // colour chosen segment
    setSegmentColor(trueCellID, -1, activePlayer)
    // TODO add 1-2 second delay after confirming move?
    Log.d("Wait", "start of wait $activePlayer")
    Thread.sleep(1000)
    Log.d("Wait", "end of wait $activePlayer")
    
    confirmMove()
}

using Thread.sleep seems to just delay all the UI updates until after all botPlayer sleeps have happened. I have also tried using Handler.postDelayed, GlobalScope.launch with a delay block and runOnUiThread with a SystemClock.sleep(1000)- these have the same problem of doing all the bot waiting, then the UI updating.

I even tried to adapt this solution a try - how to wait for Android runOnUiThread to be finished? but got the same result - big delay then all the UI updates.

Is there a fix for this or have I missed something simple?


Solution

  • As broot suggested in the comments, putting both setSegmentColor() and confirmMove() inside the postDelayed() block achieved the desired delay between botTurn()

    val botDelay = 1500L
    
            Handler().postDelayed(
                {
                    // colour chosen segment then save move
                    setSegmentColor(botMove, -1, activePlayer)
                    confirmMove(botMove)
                },
                botDelay
            )