Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to instantiate a viewmodel which extends AndroidViewModel class #44

Closed
yashasvigirdhar opened this issue May 25, 2019 · 3 comments
Closed

Comments

@yashasvigirdhar
Copy link

Hi,

First of all, thanks for open sourcing this library.

In my project, I've viewmodels which extend AndroidViewModel class, which means they want an
instance of application as a constructor parameter. I use the application context in viewmodel for two purposes:

  • to get some an instance of my application class to further have access to my dagger applicationComponent field so that I can use field injection in my viewmodel. Something like this:

MyApplication.getInstance(application).applicationComponent.inject(this)

  • to get a string resource
    (getApplication() as MyApplication).getString(R.string....

Hope that's clear.

I can't think of anyway to test this viewmodel without using Android instrumention/RoboElectric.

Do you have any ideas in mind?

@yashasvigirdhar
Copy link
Author

okay, I read about it and got to know that it's a bad practice to resolve the resources in viewmodels.we should just be setting int resource id there.
So we can eliminate the second use there.

@yashasvigirdhar
Copy link
Author

okay I read more about first thing :) , and got to know implementing a custom view model factory is the way to provide all the dependencies to viewmodel. So, it turns out that I can get rid of the context itself here. I am.gonna try it.

@jraska
Copy link
Owner

jraska commented May 27, 2019

Hello yes, I would go for the factory yes. Here there is an example implementation: https://github.com/jraska/github-client/blob/master/core-android/src/main/java/com/jraska/github/client/core/android/ViewModelFactory.kt

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants