简体   繁体   中英

Cannot create instance of ViewModel with Hilt

It looks like I have problems with using Hilt. I get the following error. Maybe I need to add something to AppModule or something. I'm not sure... 在此处输入图像描述

I use the following dependencies:

implementation "com.google.dagger:hilt-android:2.43.2"
annotationProcessor  "com.google.dagger:hilt-android-compiler:2.43.2"
implementation "androidx.hilt:hilt-lifecycle-viewmodel:1.0.0-alpha03"
annotationProcessor  "androidx.hilt:hilt-compiler:1.0.0"

My ViewModel class looks like this:

@HiltViewModel
class CurrencyViewModel  @Inject constructor(
    private val repository: CurrencyConverterImpl,
    private val dispatchers:DispatcherProvider
): ViewModel(){

The activity is like this:

@AndroidEntryPoint
class CurrencyActivity : AppCompatActivity() {
    private lateinit var binding: ActivityMainBinding
    private val viewModel: CurrencyViewModel by viewModels()

AppModule:

@Module
@InstallIn(SingletonComponent ::class)
object AppModule {
    @Singleton
    @Provides
    fun provideCurrencyApi(): CurrencyApi = Retrofit.Builder()
        .baseUrl(Utils.BASE_URL)
        .addConverterFactory(GsonConverterFactory.create())
        .build()
        .create(CurrencyApi::class.java)

    @Singleton
    @Provides
    fun provideCurrencyConverter(api: CurrencyApi): CurrencyConverter = CurrencyConverterImpl(api)

    @Singleton
    @Provides
    fun provideDispatchers(): DispatcherProvider = object : DispatcherProvider {
        override val main: CoroutineDispatcher
            get() = Dispatchers.Main
        override val io: CoroutineDispatcher
            get() = Dispatchers.IO
        override val default: CoroutineDispatcher
            get() = Dispatchers.Default
        override val unconfined: CoroutineDispatcher
            get() = Dispatchers.Unconfined

    }
}

UPDATE: It looks like Hilt didn't like that I put something to the constructor. It needed a constructor without parameters. But the question is how do I pass the CurrencyConverter repository and DispatcherProvider to ViewModel?

在此处输入图像描述 在此处输入图像描述

If I pass any parameter I also get this exception: 在此处输入图像描述

In your CurrencyViewModel constructor, try replacing:

private val repository: CurrencyConverterImpl

with:

private val repository: CurrencyConverter

Your @Provides function is providing the interface, so you need to inject the interface. Besides, that improves testability of the viewmodel, as you can supply a test double (eg, mock or fake) in unit tests.

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