Challenge - 5 Problems
ViewModel State Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ ui_behavior
intermediate2:00remaining
What is the output of this ViewModel state update?
Consider this ViewModel code that holds a counter state. What will be the value of
counter after calling increment() twice?Android Kotlin
class CounterViewModel : ViewModel() { private val _counter = MutableLiveData(0) val counter: LiveData<Int> = _counter fun increment() { _counter.value = (_counter.value ?: 0) + 1 } } // After calling increment() twice:
Attempts:
2 left
💡 Hint
Each call to increment adds 1 to the current value stored in _counter.
✗ Incorrect
The initial value is 0. Each increment adds 1, so after two calls, the value is 2.
❓ lifecycle
intermediate1:30remaining
When is ViewModel state preserved?
In Android, when does the ViewModel keep its state intact?
Attempts:
2 left
💡 Hint
Think about what happens to Activity and ViewModel during rotation.
✗ Incorrect
ViewModel survives configuration changes such as screen rotations but is cleared when the Activity is finished or the app is killed.
📝 Syntax
advanced2:00remaining
Which option correctly exposes immutable state from ViewModel?
Given a MutableStateFlow in ViewModel, which option correctly exposes it as immutable to the UI?
Android Kotlin
private val _uiState = MutableStateFlow(0)
// Expose immutable state here:Attempts:
2 left
💡 Hint
Use the correct method to expose a read-only StateFlow.
✗ Incorrect
The asStateFlow() method returns a read-only StateFlow view of the MutableStateFlow.
🔧 Debug
advanced2:30remaining
Why does UI not update after ViewModel state change?
This ViewModel updates a LiveData value, but the UI does not reflect the change. What is the likely cause?
Android Kotlin
class MyViewModel : ViewModel() { val data = MutableLiveData("Hello") fun update() { data.value = "World" } } // UI observes data but does not update after update() call.
Attempts:
2 left
💡 Hint
LiveData.value must be updated on the main thread.
✗ Incorrect
Updating LiveData.value from a background thread causes UI not to receive updates. Use postValue() or update on main thread.
🧠 Conceptual
expert3:00remaining
What is the main benefit of using StateFlow in ViewModel over LiveData?
Choose the best explanation for why StateFlow might be preferred over LiveData for state management in ViewModel.
Attempts:
2 left
💡 Hint
Think about Kotlin coroutines integration and reactive programming.
✗ Incorrect
StateFlow integrates seamlessly with Kotlin coroutines and provides a consistent reactive streams API, unlike LiveData which is lifecycle-aware but not coroutine-based.