HelloCW
HelloCW

Reputation: 2295

Is it a good idea to pass paramter repository to ViewModel instead of inherited from AndroidViewModel?

The Code A is from https://github.com/android/architecture-components-samples/tree/master/PagingWithNetworkSample

The Code B is from https://github.com/android/architecture-components-samples/tree/master/PagingSample

I know I should use AndroidViewModel instead of ViewModel when I need to use Context to instance a database based Room, just like Code B.

I find the class SubRedditViewModel in Code A doesn't inherited from AndroidViewModel, it pass the paramter repository using construction function.

Is it a good idea to pass paramter repository to ViewModel instead of inherited from AndroidViewModel ?

Code A

class SubRedditViewModel(
        private val repository: RedditPostRepository,
        private val savedStateHandle: SavedStateHandle
) : ViewModel() {
   ...
}

Code B

class CheeseViewModel(app: Application) : AndroidViewModel(app) {
    val dao = CheeseDb.get(app).cheeseDao()
    ...
}

Upvotes: 1

Views: 173

Answers (1)

Eduard B.
Eduard B.

Reputation: 6803

The moment you inherit AndroidViewModel, your class becomes less unit-testable, as you depend on the Android framework. Also, in your snippet Code B, you lost the ability to inject a test double for your dao, making testing even harder.

In conclusion, try to avoid using framework classes and practice dependency injection (manually or with the aid of a DI framework like Dagger, it doesn't matter). So your snippet Code A would be preferable.

Upvotes: 3

Related Questions