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

Функция preferencesDataStore

Функция preferencesDataStore возвращает делегат для свойства типа DataStore с данными Preferences. Его вешают на Context, имя файла задают в name, например "prefs". Запись идёт через edit, чтение - из потока data.

Синтаксис

val Context.dataStore by preferencesDataStore(name = "prefs")

Параметры

Параметр Описание
name Имя файла DataStore в каталоге приложения. Обычно совпадает с именем xml у SharedPreferences.

Пример

Давайте объявим dataStore и запишем строку:

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 { prefs -> prefs[key] = "12345" } val snapshot = dataStore.data.first() val res = snapshot[key] ?: "abcde" setContent { Text(text = res) } } } }

В DataStore "prefs" сохранится "12345" по ключу "abcde", на экране Text покажет эту строку.

Пример

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

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) } } } }

Из файла prefs прочитается снимок Preferences, на экране будет строка по ключу или "abcde".

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

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