HelloCW
HelloCW

Reputation: 2255

How can I dependency injection Context into ViewModel using Hilt in Android Studio?

Before, I use Code A to pass Context to ViewModel.

Now I hope to use Hilt as dependency injection to pass Context,

I have read the article , and Code B is from the article.

1: Is the Code B correct way to pass Context into ViewModel?

2: In my mind, in order to use Hilt in Android Studio project, I have added such as the Code C in project, do I need to use fun provideApplicationContext() = MyApplication() in Code B?

Code A

class HomeViewModel(private val mApplication: Application, val mRepository: DBRepository) : AndroidViewModel(mApplication) {
  ...
}

Code B

class MainViewModel @ViewModelInject constructor(
    @ApplicationContext private val context: Context,
    private val repository: Repository,
    @Assisted private val savedStateHandle: SavedStateHandle
) : ViewModel() {
    ...
}


@Singleton
@Provides
fun provideApplicationContext() = MyApplication()

Code C

@HiltAndroidApp
class MyApplication : Application() {
}

Upvotes: 1

Views: 3704

Answers (1)

Cj_Rodriguez
Cj_Rodriguez

Reputation: 564

This is how I injected applicationContext in the viewmodel and it worked fine.

Base Application

@HiltAndroidApp
class BaseApplication: Application()

App Module

@Module
@InstallIn(SingletonComponent::class)
object AppModule {

@Singleton
@Provides
fun provideApplication(@ApplicationContext app: Context):   BaseApplication{
    return app as BaseApplication
}

View Model

@HiltViewModel
class PendingListViewModel
@Inject
constructor(private val application: BaseApplication)

Usage In the ViewModel

AppCompatResources.getDrawable(application.applicationContext, R.drawable.marker_circle)

Upvotes: 3

Related Questions