为何在Hilt的ViewModelComponent中可将Application作为默认绑定使用?
Hilt ViewModel中可注入Application的原因
核心逻辑:组件层级的继承关系
Hilt的组件体系是分层嵌套的,ViewModelComponent作为SingletonComponent的子组件,会自动继承父组件的所有默认绑定。
Application是SingletonComponent自带的默认绑定之一,因此ViewModelComponent可以直接复用这个绑定完成注入。- 官方文档中“ViewModelComponent仅拥有SavedStateHandle这一个默认绑定”的表述,指的是ViewModelComponent自身新增的专属默认绑定,而非它能使用的全部绑定。它还能访问上层组件(如SingletonComponent)提供的所有可用绑定。
代码验证
你提供的代码中,Application能成功注入正是基于这个逻辑:
@HiltViewModel class PlaySoundViewModel @Inject constructor( private val appContext: Application, // 测试可用 private val playSound: IPlaySound, private val savedStateHandle: SavedStateHandle ): ViewModel(){ ... }
补充说明:除了Application,你还可以在ViewModel中注入其他SingletonComponent的默认绑定(比如Context,实际注入的是Application Context)。
内容的提问来源于stack exchange,提问作者HelloCW
相关产品推荐
相关产品推荐

