我DataStore<Preferences>
与 Hilt 一起使用如下。
持久性模块.kt
@Module
@InstallIn(SingletonComponent::class)
object PersistenceModule {
@Provides
@Singleton
fun provideDataStoreManager(@ApplicationContext context: Context): DataStoreManager {
return DataStoreManager(context)
}
}
数据存储管理器.kt
class DataStoreManager @Inject constructor(@ApplicationContext private val context: Context) {
private val Context.dataStore: DataStore<Preferences> by preferencesDataStore(STORE_NAME)
private suspend fun <T> DataStore<Preferences>.getFromLocalStorage(
PreferencesKey: Preferences.Key<T>, func: T.() -> Unit) {
data.catch {
if (it is IOException) {
emit(emptyPreferences())
} else {
throw it
}
}.map {
it[PreferencesKey]
}.collect {
it?.let { func.invoke(it as T) }
}
}
suspend fun <T> storeValue(key: Preferences.Key<T>, value: T) {
context.dataStore.edit {
it[key] = value
}
}
suspend fun <T> readValue(key: Preferences.Key<T>, responseFunc: T.() -> Unit) {
context.dataStore.getFromLocalStorage(key) {
responseFunc.invoke(this)
}
}
}
视图模型.kt
@HiltViewModel
class HomeViewModel @Inject constructor(
private val dataStore: DataStoreManager
) : LiveCoroutinesViewModel() {
fun readNextReviewTime() {
viewModelScope.launch {
dataStore.readValue(nextReviewTime) {
// Here you can do something with value.
}
}
}
}
更新
@HiltViewModel
class TranslateViewModel @Inject constructor(
definitionRepository: DefinitionRepository,
translateRepository: TranslateRepository,
val dataStoreManager: DataStoreManager
) : LiveCoroutinesViewModel() {
init {
readValueInViewModelScope(sourceLanguage, "ta") { // use value here }
readValueInViewModelScope(targetLanguage, "si") { // use value here }
}
private fun <T> readValueInViewModelScope(key: Preferences.Key<T>, defaultValue: T, onCompleted: T.() -> Unit) {
viewModelScope.launch {
dataStoreManager.readValue(key) {
if (this == null) {
storeValueInViewModelScope(key, defaultValue)
} else {
onCompleted.invoke(this)
}
}
}
}
fun <T> storeValueInViewModelScope(key: Preferences.Key<T>, value: T) {
viewModelScope.launch {
dataStoreManager.storeValue(key, value)
}
}
}