SQL 和 Room 儲存功能太強大了,可以用簡單一點嗎?
有的那就是用 DataStore
DataStore 是 Android Jetpack 提供的一種新的資料儲存解決方案,用於替換 SharedPreferences。它提供了一個更安全、更現代的方式來儲存鍵值對資料,並與 Kotlin Coroutines 緊密整合。
在app/build.gradle.kts 檔案的 dependencies 中:
implementation("androidx.datastore:datastore-preferences:1.0.0")
新建立 UserPreferencesRepository 的新類別
class UserPreferencesRepository(
private val dataStore: DataStore<Preferences>
){
val isLinearLayout: Flow<Boolean> = dataStore.data
.catch {
if(it is IOException) {
Log.e(TAG, "Error reading preferences.", it)
emit(emptyPreferences())
} else {
throw it
}
}
.map { preferences ->
preferences[IS_LINEAR_LAYOUT] ?: true
}
suspend fun saveLayoutPreference(isLinearLayout: Boolean) {
dataStore.edit { preferences ->
preferences[IS_LINEAR_LAYOUT] = isLinearLayout
}
}
private companion object {
val IS_LINEAR_LAYOUT = booleanPreferencesKey("is_linear_layout")
}
}
新建立 DessertReleaseApplication 的新類別
class DessertReleaseApplication: Application() {
lateinit var userPreferencesRepository: UserPreferencesRepository
override fun onCreate() {
super.onCreate()
userPreferencesRepository = UserPreferencesRepository(dataStore)
}
}
在 DessertReleaseViewModel 中使用 UserPreferencesRepository
class DessertReleaseViewModel(
private val userPreferencesRepository: UserPreferencesRepository
) : ViewModel() {
private val _uiState = MutableStateFlow(DessertReleaseUiState())
// UI states access for various [DessertReleaseUiState]
val uiState: StateFlow<DessertReleaseUiState> =
userPreferencesRepository.isLinearLayout.map { isLinearLayout ->
DessertReleaseUiState(isLinearLayout)
}
.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5_000),
initialValue = DessertReleaseUiState()
)
/*
* [selectLayout] change the layout and icons accordingly and
* save the selection in DataStore through [userPreferencesRepository]
*/
fun selectLayout(isLinearLayout: Boolean) {
viewModelScope.launch {
userPreferencesRepository.saveLayoutPreference(isLinearLayout)
}
}
companion object {
val Factory: ViewModelProvider.Factory = viewModelFactory {
initializer {
val application = (this[APPLICATION_KEY] as DessertReleaseApplication)
DessertReleaseViewModel(application.userPreferencesRepository)
}
}
}
}
https://developer.android.com/codelabs/basic-android-kotlin-compose-navigation?hl=zh-tw