1

I'm making a trivia game that fetches questions from an API service. I have code like this in my view model.

private var _currentQuestion = MutableLiveData<TriviaQuestion>()
val currentQuestion: LiveData<TriviaQuestion> = _currentQuestion

fun resetGameState() {
    _currentQuestion = MutableLiveData()
}

Essentially there are points in my app where I need to reset the whole game state. I find if I re-assign my mutable live data like this, the app uses this empty value, even though resetGameState() is called first, and afterwards _currentQuestion's value is updated with the fetched value.

This live data is data binded in my layout, and there's the appropriate call to setting the lifecycle owner of it.

I'm not sure if there's a good way to reset live data that is instantiated with MutableLiveData<>(). You could chuck in dummy empty data (like an empty string if it's ) but I'd like to avoid that.

SmallGrammer
  • 893
  • 9
  • 19
  • You might reset by this. However, `currentQuestion` is referencing the previous object of `_currentQuestion` and the same for the current observers. – Tuan Chau May 30 '21 at 02:33

1 Answers1

2

The 'default' value when you create an instance of MutableLiveData in your example, is null. So if you're just looking to set it to the same value as it started with, you should just set it to null:

_currentQuestion.value = null
Henry Twist
  • 5,666
  • 3
  • 19
  • 44
  • I think this will work, but I would have to turn my live data type to be nullable to assign it null, which will have a flow on effect with the rest of the code. – SmallGrammer May 30 '21 at 02:59
  • I actually don't think that's the case, although I can't test it currently. `LiveData` is a Java library not a Kotlin one, so it will accept the null values regardless. However what value would you expect it to hold if it was 'reset'? – Henry Twist May 30 '21 at 09:07