我可以在另一个模块 hilt 中注入 Singleton 自定义对象吗

can I inject Singleton custom object in another module hilt

我正在尝试将 MyPreference class 对象注入到 NetworkModule 以及 activity 中,在 activity 中它工作正常,但在 NetworkModule 中它仍未初始化。由于改造需要这个对象来获取 accessToken,所以我在 NetworkModule 中需要这个。但不工作

这是我的代码

@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)
    }

}

Hilt 模块不应包含变量,因此 @Inject 注释不会有任何效果。

您应该将 MyPreference 作为参数传递给需要它的提供程序 - 只有这样 Hilt 才会注入它。

例如:

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

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

在我的代码片段中 MyPreference 应该被注入

为了清楚起见,我编了 RetrofitClass :)