I am attempting to get the number of lives into the quiz. What seems to happen is that the number of lives from the preferences datastore is stored into the variable, yet when it comes to actually using it in the quiz, it doesn't seem to change at all from the initial variable value of 1.
class ActivityGame : AppCompatActivity() {
var int_lives: Int = 1
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_question_multiple_choice_question)
gameCurrencyManager = gameCurrencyManager(this)
setInGameCurrencyFromGameCurrencyManager()
loadQuestion()
}
fun loadQuestion(){
Log.d("tag_NumberOfLives", int_lives.toString())
if(int_energyDrinksTotal <= 0){
//Message Dialog Box
}
}
fun setInGameCurrencyFromGameCurrencyManager(){
gameCurrencyManager.getLives.asLiveData().observe(this) {
int_lives = it
Log.d("tag_NumberOfLivesToBeAdded", int_lives.toString())
textview_lives.setText("$int_lives", TextView.BufferType.EDITABLE)
}
}
}
This resulted in the "tag_NumberOfLivesToBeAdded" to print out 5, as expected; however, when it came to the "tag_NumberOfLives", once the quiz was starting to run, the result was 1.
I have attempted to make the variable int_lives to Delegates.notNull() but that resulted in an exception, but since I cannot make the variable a lateinit.
Observing the live data is asynchronous, so the variable will be set slightly in the future, after you’ve already called your
loadQuestion()function.The quick and dirty solution would be to read the preference by using
runBlockingandfirst()on the flow. You’re not supposed to read files on the main thread like this, but probably your preferences file is tiny and won’t be at risk of noticeably freezing the app. It would only make sense to do this if you only need to read the value once each time the activity starts (as opposed to every time you write a new value to the preferences), which seems to be the case here.The more proper way to do this is to wait for the value to arrive without blocking and only after it arrives start doing the stuff that depends on it being available:
If you thought the data was going to take a while to load you could set a content view that shows some kind of loading screen before you launch the coroutine.