📱

[Android]DataStoreとJetpack Compose

2024/04/17に公開

DataStoreとは

Googleが推奨している小規模データ永続化の方法
2種類ある
Preferences DataStore
type safeではない(コンパイラが型を保証しない)
プリミティブな型のみ

→Proto DataStore
type safe
カスタムクラスも可能

今回はPreferences DataStoreのみ

使用方法

依存関係

build.gradle
implementation("androidx.datastore:datastore-preferences:1.0.0")
val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = "settings")
val IS_FIRST_LAUNCH = booleanPreferencesKey("is_first_launch")

@Composable
fun SampleDataStore(
    modifier: Modifier = Modifier
) {
    val context = LocalContext.current
    val scope = rememberCoroutineScope()
    val isFirstLaunch = remember { mutableStateOf(false) }

    LaunchedEffect(Unit) {
        context.dataStore.data
            .map { preferences ->
                preferences[IS_FIRST_LAUNCH] ?: false
            }
            .collect {
                isFirstLaunch.value = it
            }
    }
    
    Column(
        modifier = modifier.fillMaxSize(),
        verticalArrangement = Arrangement.Center,
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        Text(text = isFirstLaunch.value.toString(), fontSize = 50.sp)
        Button(
            onClick = {
                scope.launch { 
                    saveIsFirstDataStore(context)
                }
            }
        ) {
            Text(text = "save")
        }
    }
}

suspend fun saveIsFirstDataStore(context: Context) {
    context.dataStore.edit { settings ->
        settings[IS_FIRST_LAUNCH] = true
    }
}

https://developer.android.com/topic/libraries/architecture/datastore

Discussion