11

我有一个 sharedPreference 对象,我想通过项目将其作为依赖注入组件。

// sharedPreference object
private const val PREF_TAG = "tag"
object MyPreference {
    fun getStoredTag(context: Context): String {
        val prefs = PreferenceManager.getDefaultSharedPreferences(context)
        return prefs.getString(PREF_TAG, "")!!
    }
    fun setStoredTag(context: Context, query: String) {
        PreferenceManager.getDefaultSharedPreferences(context)
            .edit()
            .putString(PREF_TAG, query)
            .apply()
    }
}

// How to correctly inject the sharedPreference?
// create a module?
@Module
@InstallIn(SingletonComponent::class)
object PreferenceModule {
    @Provides
    @Singleton
    fun provideSharedPreference(): SharedPreferences {
        return MyPreference()
    }
}
// or directly inject in viewModel
class LoginViewModel @ViewModelInject constructor(
    application: Application,
    myPreference: MyPreference
) : AndroidViewModel(application) {
    ...
}
// or another way?
4

2 回答 2

19

这是一个基于意见的答案,但至少我会给你一个遵循的方向。


您通常会SharedPreferences在包装类中维护一个实例。所以...

  1. 使用常规class而不是object声明
  2. 既然要Hilt设置,可以直接对类使用hilt注解,直接注入Context到构造函数中
@Singleton
class MyPreference @Inject constructor(@ApplicationContext context : Context){
    val prefs = PreferenceManager.getDefaultSharedPreferences(context)

    fun getStoredTag(): String {
        return prefs.getString(PREF_TAG, "")!!
    }
    fun setStoredTag(query: String) {
        prefs.edit().putString(PREF_TAG, query).apply()
    }
}
  1. 然后你不需要 a Module,你可以简单地使用@ViewModelInject
class LoginViewModel @ViewModelInject constructor(
    application: Application,
    myPreference: MyPreference
) : AndroidViewModel(application) {
    ...
}
于 2020-08-31T09:15:06.763 回答
5

使用 Hilt 2.38.1:

SharedPreferencesModule.kt

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

    @Singleton
    @Provides
    fun provideSharedPreference(@ApplicationContext context: Context): SharedPreferences {
        return context.getSharedPreferences("preferences_name", Context.MODE_PRIVATE)
    }
}

自定义视图模型.kt

@HiltViewModel
class CustomViewModel @Inject constructor(
    private val sharedPreferences: SharedPreferences
):ViewModel() {

    fun customFunction() {
        sharedPreferences.edit().putString("firstStoredString", "this is the content").apply()

        val firstStoredString = sharedPreferences.getString("firstStoredString", "")
    }
    ...
于 2021-09-28T19:34:04.247 回答