AndroidViewModel对比直接传入Application上下文的技术疑问
Answers to AndroidViewModel Questions
Awesome questions—let's unpack these one by one to clear up the confusion!
Q1: What benefits does AndroidViewModel provide if we still have to pass Application in the constructor?
Even though you still pass Application to its constructor, AndroidViewModel offers several practical, developer-friendly advantages:
- Clear semantic signaling: By extending
AndroidViewModelinstead of the baseViewModel, you're explicitly telling other developers (and your future self) that this component depends on the application-level context. This makes your code more readable and self-documenting—no need to guess if a regularViewModelholds aContextand what type it is. - Built-in application access: You don't need to store the
Applicationinstance as a separate property in your ViewModel. The class already holds it internally, and you can retrieve it anytime using thegetApplication()method (or directly access it in Kotlin since it's exposed as a property). - Seamless integration with official factories: When using the default
ViewModelProvider.AndroidViewModelFactory(the factory used by default in most cases), it automatically injects theApplicationinstance into yourAndroidViewModelconstructor. You don't have to write custom factory code or manually passApplicationwhen initializing the ViewModel—simply callViewModelProvider(this).get(YourViewModel::class.java)and it works.
Q2: Why use AndroidViewModel instead of just passing Application to a regular ViewModel?
Good question—while technically you could pass Application to a base ViewModel, using AndroidViewModel is the better choice for these reasons:
- Enforces architecture best practices: Jetpack's architecture components are designed to provide standardized, safe patterns.
AndroidViewModelis the official solution for ViewModels that need application context, so using it aligns your code with Google's recommended practices, reducing the chance of anti-patterns. - Prevents accidental memory leaks: Since
AndroidViewModelonly acceptsApplication(a global, lifecycle-independent context), it eliminates the risk of accidentally passing anActivityorFragmentcontext to your ViewModel. Those component-specific contexts have shorter lifecycles, and holding onto them in a ViewModel (which outlives components) would cause memory leaks.AndroidViewModellocks you into using the safe, application-level context. - Reduces boilerplate code: If you use a base
ViewModelwithApplication, you'd have to create a customViewModelFactoryto pass theApplicationinstance every time you initialize the ViewModel.AndroidViewModelworks out of the box with the default factory, so you skip writing that repetitive setup code.
内容的提问来源于stack exchange,提问作者Refael Sheinker
相关产品推荐
相关产品推荐

