1

I'm trying to inject the Context in my ModelView but I'm a little bit confused:

Here is my Module, I send him an Application for later use the context from this, but I don't know where it comes from this Application or how to take it:

@Module
class module {
    @Provides @Singleton fun appContext(application: Application): Context{
        return application
    }
}

And here is my Component:

@Component(modules = [module::class])
interface component {
    fun providesApplication(): Application
}

To finish I don't know how to inject this in my ViewModel because this don't have constructor to inject it.

How should I inject the context to my ViewModel?

David
  • 414
  • 7
  • 17

2 Answers2

4

There is already build-in ViewModel with context, replace inheritance from ViewModel with AndroidViewModel

See: https://developer.android.com/reference/android/arch/lifecycle/AndroidViewModel

Maksym V.
  • 2,877
  • 17
  • 27
  • And how I should replace this line: viewModel = ViewModelProviders.of(this).get(MainViewModel::class.java) because it jumps me an alert. – David Jul 22 '19 at 10:12
1

alternatively, you could try something like this :

class YourViewModel @Inject constructor(context:Context) : ViewModel()

Merely a suggestion if nothing else works, hear me out...

var context: Context? = null

fun initViewModelWithContext(context: Context) {
    this.context = context
}

you could potentially do something like this as well, if you don't find a solution with dagger. all your functions can then use this local instance of context, and this ViewModel will be destroyed/created as it is needed so it won't be causing any memory issues

a_local_nobody
  • 7,947
  • 5
  • 29
  • 51
  • Interesting... but then I should inject the a constructor instead of a Context? I don't know how to finish it. – David Jul 22 '19 at 10:20
  • The context is required, because I have a few fun who need it. However, I try what you say but the thing Is I need to make the builder and it usually done in the constructor. – David Jul 22 '19 at 10:26
  • I think what you are trying to made is inject a full constructor to my ViewModel right? – David Jul 22 '19 at 10:27