Dagger Hilt @ViewModelInject is deprecated how to use @ApplicationContext in @HiltViewModel

I’m using @ViewModelInject in my ViewModel as shown in below but now It’s deprecated so When I tried to use @HiltViewModel but I can’t use @ApplicationContext init.

So my question is How to use common dependency which I annotated with @InstallIn(SingletonComponent::class) in @HiltViewModel ?

How to use @ApplicationContext in @HiltViewModel , ViewModelComponent::class ?

My code Which Work fine with @ViewModelInject are below

1. AppModule()

@Qualifier
@Retention(AnnotationRetention.BINARY)
annotation class SplashApiInterface

@Module
@InstallIn(SingletonComponent::class)
class AppModule() {
    internal var pref_name = Common.pref_name

    @Provides
    @Singleton
    fun mySharedPreference(@ApplicationContext context: Context): SharedPreferences {
        return context.getSharedPreferences(pref_name, Context.MODE_PRIVATE)
    }

    @Provides
    @Singleton
    fun connectionDetector(@ApplicationContext context: Context): ConnectionDetector {
        return ConnectionDetector(context)
    }

    @Provides
    fun myCompositeDisposable(): CompositeDisposable {
        return CompositeDisposable()
    }

    @SplashApiInterface
    @Provides
    @Singleton
    fun mAPIServiceSplash(@ApplicationContext context: Context): ApiInterface {
        return ApiUtils.getAPIServiceSpl(context)
    }

}`

2.SplashVModel

@ActivityScoped
@Singleton
class SplashVModel @ViewModelInject constructor(@ApplicationContext val context: Context,
                                                val sharedPreferences: SharedPreferences,
                                                @SplashApiInterface val mAPIService: ApiInterface,
                                                val myCompositeDisposable: CompositeDisposable,
                                                var cd: ConnectionDetector
) : ViewModel() {
    
    // here I removed use cases of constructor value for brevity

    }

}

So now if I use @HiltViewModel how to use SingletonComponent common function? Now If create ViewModelComponent::class then how to
use that common function again in this? So What should I do ? Do I
have to remove all common cases from SingletonComponent and use
individually in each ViewModel()?

Source: Android Questions

LEAVE A COMMENT