【筆記】Android Jetpack 的 DataStore 介紹(By ChatGPT)

DataStore 是一個新的輕量級數據存儲解決方案,可替代 SharedPreferences,並提供更多的功能和安全性。在 Jetpack Compose 中,您可以使用 DataStore 來存儲和讀取應用程序的配置和狀態數據。

以下是一個簡單的範例,展示了如何在 Jetpack Compose 中使用 DataStore:

data class UserSettings(val darkThemeEnabled: Boolean, val notificationEnabled: Boolean)

class UserSettingsRepository(private val dataStore: DataStore<Preferences>) {
    companion object {
        val DARK_THEME_ENABLED = booleanPreferencesKey("dark_theme_enabled")
        val NOTIFICATION_ENABLED = booleanPreferencesKey("notification_enabled")
    }

    val userSettingsFlow: Flow<UserSettings> = dataStore.data
        .map { preferences ->
            UserSettings(
                darkThemeEnabled = preferences[DARK_THEME_ENABLED] ?: false,
                notificationEnabled = preferences[NOTIFICATION_ENABLED] ?: true
            )
        }

    suspend fun updateUserSettings(userSettings: UserSettings) {
        dataStore.edit { preferences ->
            preferences[DARK_THEME_ENABLED] = userSettings.darkThemeEnabled
            preferences[NOTIFICATION_ENABLED] = userSettings.notificationEnabled
        }
    }
}

@Composable
fun SettingsScreen(userSettingsRepository: UserSettingsRepository) {
    val userSettings by userSettingsRepository.userSettingsFlow.collectAsState(UserSettings(false, true))

    // Composables to display user settings and update user settings
}

在這個範例中,我們創建了一個 UserSettingsRepository 類別,其中有一個 userSettingsFlow 用於返回存儲在 DataStore 中的用戶設置。在 SettingsScreen Composable 函數中,我們使用 userSettingsRepository.userSettingsFlow.collectAsState 函數將 userSettingsFlow 轉換為可應用於 Composable 的狀態。

最後,我們使用 Composables 顯示用戶設置和更新用戶設置。當用戶更改設置時,我們可以調用 userSettingsRepository.updateUserSettings 函數來更新 DataStore 中的用戶設置。

這是一個簡單的例子,演示了如何在 Jetpack Compose 中使用 DataStore。您可以通過自定義 Preferences.Key 來添加更多的數據字段,或者通過使用 Proto DataStore 將 Protobuf 數據序列化到 DataStore 中。DataStore 為應用程序提供了一個更安全、更強大的數據存儲解決方案,特別是對於需要存儲和讀取敏感數據的應用程序。


留言

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *