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

Класс DataStore

Класс DataStore - интерфейс асинхронного хранилища. Для настроек его получают через preferencesDataStore с типом Preferences. Текущие данные приходят из data, изменения пишут suspend-методом edit.

Синтаксис

dataStore.edit { prefs -> prefs[key] = "12345" }

Методы

Метод Описание
edit Атомарно меняет данные в файле и возвращает новый снимок.

Пример

Давайте запишем строку в DataStore prefs:

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

edit сохранит "12345" в prefs, на экране Text покажет прочитанное значение.

Пример

Давайте подпишемся на data и обновим 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.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import androidx.datastore.preferences.core.stringPreferencesKey import androidx.datastore.preferences.preferencesDataStore import androidx.lifecycle.lifecycleScope import kotlinx.coroutines.flow.collect 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") var label by mutableStateOf("abcde") lifecycleScope.launch { dataStore.data.collect { snapshot -> label = snapshot[key] ?: "abcde" } } setContent { Text(text = label) } } }

При каждом новом снимке Preferences на экране обновится строка из DataStore.

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

  • метод edit,
    которым пишут изменения
  • функция preferencesDataStore,
    которой создают экземпляр
  • класс Preferences,
    который edit возвращает и шлёт data
  • класс SharedPreferences,
    синхронная альтернатива xml
← →
↑
Мы используем cookie для работы сайта, аналитики и персонализации. Обработка данных происходит согласно Политике конфиденциальности.
принять все настроить отклонить