代码A来自https://github.com/android/architecture-components-samples/tree/master/PagingWithNetworkSample
代码B来自https://github.com/android/architecture-components-samples/tree/master/PagingSample
我知道我应该使用AndroidViewModel
而不是ViewModel
在需要使用Context
实例来基于数据库的Room(例如代码B)时使用。
我发现SubRedditViewModel
代码A中的类未继承自AndroidViewModel
,它repository
使用构造函数传递了参数。
将参数传递repository
给ViewModel
而不是继承自是一个好主意AndroidViewModel
吗?
代码A
class SubRedditViewModel(
private val repository: RedditPostRepository,
private val savedStateHandle: SavedStateHandle
) : ViewModel() {
...
}
代码B
class CheeseViewModel(app: Application) : AndroidViewModel(app) {
val dao = CheeseDb.get(app).cheeseDao()
...
}
继承的那一刻AndroidViewModel
,由于您依赖于Android框架,因此您的类变得不可单元测试。另外,在代码段B中,您失去了为自己的测试插入两倍的能力dao
,从而使测试更加困难。
总之,请尝试避免使用框架类并练习依赖项注入(手动或借助Dagger这样的DI框架都没关系)。因此,您最好使用代码段A。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句