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

Метод edit

Метод edit у DataStore - suspend-функция. Она принимает лямбду, которая меняет изменяемый снимок Preferences, сохраняет файл и возвращает новый неизменяемый Preferences. Ключи задают функциями вроде stringPreferencesKey.

Синтаксис

dataStore.edit { prefs -> prefs[stringPreferencesKey("abcde")] = "12345" }

Параметры

Параметр Описание
transform Suspend-лямда с изменяемым Preferences. Внутри присваивают prefs[key] = value или удаляют ключ.

Пример

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

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

edit сохранит "12345" в prefs, возвращённый снимок даст ту же строку для Text на экране.

Пример

Давайте изменим int и boolean в одном edit:

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.booleanPreferencesKey import androidx.datastore.preferences.core.edit import androidx.datastore.preferences.core.intPreferencesKey import androidx.datastore.preferences.preferencesDataStore import androidx.lifecycle.lifecycleScope import kotlinx.coroutines.launch private val Context.dataStore by preferencesDataStore(name = "prefs") class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val intKey = intPreferencesKey("abcde") val boolKey = booleanPreferencesKey("12345") lifecycleScope.launch { val snapshot = dataStore.edit { prefs -> prefs[intKey] = 12345 prefs[boolKey] = true } val res = snapshot[intKey]?.toString() ?: "abcde" setContent { Text(text = res) } } } }

Оба ключа запишутся в prefs за один edit, на экране Text покажет "12345" из int.

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

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