can I inject Singleton custom object in another module hilt

Viewed 375

I am trying to inject MyPreference class object into a NetworkModule as well as in activity, inside activity it is working fine but in NetworkModule it remain uninitialised. Since retrofit need this object to get accessToken, I need this in NetworkModule. but not working

here is my code

@Singleton
class MyPreference @Inject constructor(@ApplicationContext context : Context) {
    private val prefs: SharedPreferences =
        context.getSharedPreferences(context.getString(R.string.app_name), Context.MODE_PRIVATE)

    fun getStoredTag(): String? =
        prefs.getString("TOKEN", "")

    fun setStoredTag(token: String) {
        prefs.edit().putString("TOKEN", token).apply()

    }
}

@Module
@InstallIn(SingletonComponent::class)
class NetworkModule {

    @Inject
    lateinit var myPreference: MyPreference

    // retrofit stuffs
}
@Module
@InstallIn(SingletonComponent::class)
class SharedPrefModule {
    @Provides
    @Singleton
    fun providePreference(@ApplicationContext context: Context): MyPreference {
        return MyPreference(context)
    }

}
1 Answers

Hilt module should not contain variables, so the @Inject annotating won't have any effect.

You should pass MyPreference as a parameter in the provider that needs it - only then Hilt will inject it.

For example:

@Module
@InstallIn(SingletonComponent::class)
class NetworkModule {

    // retrofit stuffs
    @Provider
    fun provideRetrofitClass(
        myPreference: MyPreference
    ): RetrofitClass {
        // Use MyPreference here to fetch RetrofitClass
    }
}

In my code snippet MyPreference should be injected

Just to be clear, I made up RetrofitClass :)

Related