Found a small flaw in the logic after finishing Chapter 4: Debugging.
Problem:
When we are finished with the app and we check whether we have something in our savedInstanceState
or not we either go with restore or reset the game.
if (savedInstanceState != null) { score = savedInstanceState.getInt(SCORE_KEY) timeLeft = savedInstanceState.getInt(TIME_LEFT_KEY) restoreGame() } else { resetGame() }
If you rotate the app before you even tap the button you will save the initial values. Time left as 60 and score as 0. And now when we have values in state we will continue with restoring the game which in turn will begin the countdown.
Solution:
Maybe this isn’t the best solution but it solves the problem and is not more complicated.
First we add a new value to our companion object
to be able to know if we started the game or not.
private val ONGOING_GAME_KEY = “ONGOING_GAME_KEY”
then instead of the if-case in onCreate
we have this
score = savedInstanceState?.getInt(SCORE_KEY) ?: score
timeLeft = savedInstanceState?.getInt(TIME_LEFT_KEY) ?: timeLeft
gameStarted = savedInstanceState?.getBoolean(ONGOING_GAME_KEY) ?: gameStarted
if (gameStarted) restoreGame() else resetGame()