0
0
Android Kotlinmobile~20 mins

ViewModel creation in Android Kotlin - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
ViewModel Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
📝 Syntax
intermediate
2:00remaining
Correct ViewModel class declaration
Which option correctly declares a simple ViewModel class in Kotlin for Android?
Aclass MyViewModel : ViewModel() {}
Bclass MyViewModel extends ViewModel {}
Cclass MyViewModel : ViewModel {}
Dfun MyViewModel() : ViewModel {}
Attempts:
2 left
💡 Hint
Remember Kotlin uses ':' for inheritance and parentheses for constructor calls.
ui_behavior
intermediate
2:00remaining
ViewModel lifecycle behavior
What happens to a ViewModel instance when the associated Activity is rotated (configuration change)?
AThe ViewModel is destroyed and recreated with the Activity.
BThe ViewModel instance is retained and reused by the new Activity instance.
CThe ViewModel is paused and resumed after rotation.
DThe ViewModel is converted to a singleton shared across all Activities.
Attempts:
2 left
💡 Hint
Think about how ViewModel helps keep UI data during screen rotations.
🧠 Conceptual
advanced
2:00remaining
Purpose of ViewModel in MVVM architecture
What is the main role of a ViewModel in the MVVM pattern on Android?
ATo handle UI rendering and user input directly.
BTo replace the Activity and Fragment lifecycle methods.
CTo store and manage UI-related data and handle business logic separate from UI.
DTo manage database connections and network calls only.
Attempts:
2 left
💡 Hint
ViewModel acts as a bridge between UI and data layers.
🔧 Debug
advanced
2:00remaining
Identify the error in ViewModel usage
What error will occur with this code snippet? val viewModel = ViewModelProvider(this).get(MyViewModel::class.java) class MyViewModel {}
Android Kotlin
val viewModel = ViewModelProvider(this).get(MyViewModel::class.java)

class MyViewModel {}
ANo error, code runs correctly.
BCompile error: Missing parentheses in ViewModelProvider constructor.
CRuntime error: ViewModelProvider requires a Fragment, not Activity.
DCompile error: MyViewModel must extend ViewModel class.
Attempts:
2 left
💡 Hint
Check if MyViewModel inherits from the correct base class.
navigation
expert
2:00remaining
ViewModel sharing between fragments
How can two fragments in the same Activity share the same ViewModel instance?
AUse ViewModelProvider with the Activity as the owner for both fragments.
BCreate separate ViewModel instances in each fragment using their own ViewModelProvider(this).
CPass ViewModel instance manually via fragment arguments bundle.
DUse a singleton ViewModel instance created outside the Activity.
Attempts:
2 left
💡 Hint
Think about the lifecycle owner scope when requesting ViewModel.