Reputation: 1383
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.
Upvotes: 2
Views: 5069
Reputation: 5980
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
Upvotes: 2