Создаем портфолио за 1 месяц
К концу месяца: 4 классных проекта в вашем портфолио! Стоимость: 100$. Подробности...
437 of 502 menu
◀ ▶

Класс Preferences

Класс Preferences описывает один снимок настроек из DataStore. Его отдаёт поток data и возвращает edit после записи. Значение читают как preferences[key], где key создают через stringPreferencesKey и похожие функции. Отдельных методов у снимка нет: это карта ключ-значение на момент чтения.

Синтаксис

val res = snapshot[stringPreferencesKey("abcde")]

Пример

Давайте прочитаем строку из снимка Preferences:

import android.content.Context import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.material3.Text import androidx.datastore.preferences.core.edit import androidx.datastore.preferences.core.stringPreferencesKey import androidx.datastore.preferences.preferencesDataStore import androidx.lifecycle.lifecycleScope import kotlinx.coroutines.flow.first import kotlinx.coroutines.launch private val Context.dataStore by preferencesDataStore(name = "prefs") class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val key = stringPreferencesKey("abcde") lifecycleScope.launch { dataStore.edit { it[key] = "12345" } val snapshot = dataStore.data.first() val res = snapshot[key] ?: "abcde" setContent { Text(text = res) } } } }

Снимок Preferences даст "12345" по ключу "abcde", на экране будет та же строка.

Пример

Давайте вернём запасное значение для пустого ключа:

import android.content.Context import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.material3.Text import androidx.datastore.preferences.core.stringPreferencesKey import androidx.datastore.preferences.preferencesDataStore import androidx.lifecycle.lifecycleScope import kotlinx.coroutines.flow.first import kotlinx.coroutines.launch private val Context.dataStore by preferencesDataStore(name = "prefs") class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val key = stringPreferencesKey("abcde") lifecycleScope.launch { val snapshot = dataStore.data.first() val res = snapshot[key] ?: "abcde" setContent { Text(text = res) } } } }

Если ключа нет, прочитается "abcde" как значение по умолчанию в коде.

Смотрите также

  • класс DataStore,
    откуда приходят снимки Preferences
  • метод edit,
    который меняет данные перед новым снимком
  • функция stringPreferencesKey,
    которой задают ключ для чтения
  • класс SharedPreferences,
    где чтение идёт через get-методы
← →
↑
Мы используем cookie для работы сайта, аналитики и персонализации. Обработка данных происходит согласно Политике конфиденциальности.
принять все настроить отклонить