将paramter存储库传递给ViewModel而不是从AndroidViewModel继承是个好主意吗



代码A来自https://github.com/android/architecture-components-samples/tree/master/PagingWithNetworkSample

代码B来自https://github.com/android/architecture-components-samples/tree/master/PagingSample

我知道当我需要使用Context来实例化基于数据库的Room时,我应该使用AndroidViewModel而不是ViewModel,就像代码B一样。

我发现代码A中的类SubRedditViewModel不是从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会更好。

最新更新