Код: Выделить всё
interface TripListRepository {
suspend fun saveListDataTile(data: MutableList)
suspend fun getListDataTile(): MutableList}
val Context.dataStore: DataStore by dataStore(fileName = "TRIP_LIST", serializer = TripListSerializer)
class TripListRepositoryImpl @Inject constructor(
@ApplicationContext private val context: Context,
) : TripListRepository {
override suspend fun saveListDataTile(data: MutableList) {
context.dataStore.updateData { it.copy(tripList = data) }
}
override suspend fun getListDataTile(): MutableList = context.dataStore.data.first().tripList
Код: Выделить всё
object TripListSerializer : Serializer {
override val defaultValue: TripListData = TripListData(mutableListOf())
override suspend fun readFrom(input: InputStream): TripListData {
return try {
Json.decodeFromString(
deserializer = TripListData.serializer(),
string = input.readBytes().decodeToString()
)
} catch (e: SerializationException) {
Log.d("error read from method", e.message.orEmpty())
defaultValue
}
}
override suspend fun writeTo(t: TripListData, output: OutputStream) {
output.write(
Json.encodeToString(
serializer = TripListData.serializer(),
value = t
).encodeToByteArray()
)
}
Код: Выделить всё
private fun onNextClicked() {
val item = TripListItemData(
city = _uiState.value.toCityName,
country = _uiState.value.toCountryName,
date = _uiState.value.date.let { it.convertMillisToDate(it) }
)
viewModelScope.launch {
runCatching {
if (tripListRepository.getListDataTile().isEmpty()) {
tripListRepository.saveListDataTile(data = mutableListOf(item))
} else {
tripListRepository.getListDataTile().add(item)
_navigationEvents.trySend(TripDataDetailsNavigationEvent.OnNextClicked)
}
}
}
}
viewModelScope.launch {
runCatching {
_uiState.update {
it.copy(
tripList = repository.getListDataTile())}}}
Подробнее здесь: https://stackoverflow.com/questions/792 ... -lost-data