ccd*_*ccd 6 android dagger-hilt
我有一个 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?
Run Code Online (Sandbox Code Playgroud)
ivo*_*oto 19
使用希尔特 2.38.1:
共享首选项模块.kt
@Module
@InstallIn(SingletonComponent::class)
class SharedPreferencesModule {
@Singleton
@Provides
fun provideSharedPreference(@ApplicationContext context: Context): SharedPreferences {
return context.getSharedPreferences("preferences_name", Context.MODE_PRIVATE)
}
}
Run Code Online (Sandbox Code Playgroud)
自定义ViewModel.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", "")
}
...
Run Code Online (Sandbox Code Playgroud)
Bar*_*ski 14
这是一个基于意见的答案,但至少我会给你一个方向。
您通常会SharedPreferences在包装类中维护一个实例。所以...
class而不是object声明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()
}
}
Run Code Online (Sandbox Code Playgroud)
Module,你可以简单地使用@ViewModelInjectclass LoginViewModel @ViewModelInject constructor(
application: Application,
myPreference: MyPreference
) : AndroidViewModel(application) {
...
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2882 次 |
| 最近记录: |