2025.2.26
依赖库需求
项目级build.gradle
buildscript {
dependencies {
classpath ("com.google.dagger:hilt-android-gradle-plugin:2.51.1") // Hilt 插件,建议自动修复到最新版,版本过低会出现 viewmodel阶段的<init>异常
}
}
模块级build.gradle
plugins {
id("kotlin-kapt")
id ("dagger.hilt.android.plugin")
}
dependencies {
implementation (libs.androidx.datastore.preferences)
implementation("androidx.lifecycle:lifecycle-viewmodel-compose:2.8.4")
implementation (libs.hilt.android)
kapt (libs.hilt.compiler)
}
实现操作
新建APP类,添加hilt注解
package com.luoling.yoruplayermobile
import android.app.Application
import dagger.hilt.android.HiltAndroidApp
@HiltAndroidApp
class YoruApplication : Application()
在MainActivity里打上Hilt入口注解
@AndroidEntryPoint
class MainActivity : ComponentActivity() {....}
修改manifest
<application
android:name=".YoruApplication">
......
封装DataStore,读取用flow处理实现自动更新
class DataStoreManager(private val dataStore:DataStore<Preferences>) {
suspend fun editPreference(key:String,value:String){
val stringKey=stringPreferencesKey(key)
dataStore.edit { preferences ->
preferences[stringKey]=value
}
}
fun readPreference(key:String):Flow<String>{
val stringKey=stringPreferencesKey(key)
return dataStore.data.map {
preferences ->
preferences[stringKey]?:"null"
}
}
suspend fun editIntPreference(key: String, value: Int) {
val intKey = intPreferencesKey(key)
dataStore.edit { preferences ->
preferences[intKey] = value
}
}
fun readIntPreference(key: String): Flow<Int> {
val intKey = intPreferencesKey(key)
return dataStore.data.map { preferences ->
preferences[intKey] ?: 0
}
}
}
di层实现提供单例,最新版DataStore需要使用工厂,hilt自动解析provides注解提供的函数池寻找填充隐式依赖完成依赖链
@Module
@InstallIn(SingletonComponent::class)
class DataStoreModule {
@Provides
@Singleton
fun providePreferencesDataStore(@ApplicationContext context:Context):DataStore<Preferences>{
return PreferenceDataStoreFactory.create (
produceFile = { context.preferencesDataStoreFile("settings") }
)
}
@Provides
@Singleton
fun provideDataStoreManager(dataStore: DataStore<Preferences>):DataStoreManager{
return DataStoreManager(dataStore)
}
}
ViewModel中使用hiltviewmodel和inject注解完成注入
@HiltViewModel
class UserHomeViewModel @Inject constructor(
private val dataStoreManager: DataStoreManager
) : ViewModel() {
var tmp by mutableStateOf("114514")
private set // 限制仅在 ViewModel 内修改
suspend fun savePreference(key: String, value: String) {
dataStoreManager.editPreference(key, value)
}
init {
viewModelScope.launch {
dataStoreManager.readPreference("key")
.collect { value ->
tmp = value
}
}
}
}