简体   繁体   中英

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() {
}

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM