From 09b5d536cb174de66fe5a37aea106bf7c3eea9f4 Mon Sep 17 00:00:00 2001 From: johan12345 Date: Mon, 15 Aug 2022 20:53:22 +0200 Subject: [PATCH] keep ChargerDetails in saved state fixes #205 --- .../net/vonforst/evmap/viewmodel/MapViewModel.kt | 9 ++++++++- .../main/java/net/vonforst/evmap/viewmodel/Utils.kt | 13 ++++++++++--- 2 files changed, 18 insertions(+), 4 deletions(-) diff --git a/app/src/main/java/net/vonforst/evmap/viewmodel/MapViewModel.kt b/app/src/main/java/net/vonforst/evmap/viewmodel/MapViewModel.kt index 2dd539a3..b47b8d63 100644 --- a/app/src/main/java/net/vonforst/evmap/viewmodel/MapViewModel.kt +++ b/app/src/main/java/net/vonforst/evmap/viewmodel/MapViewModel.kt @@ -141,17 +141,24 @@ class MapViewModel(application: Application, private val state: SavedStateHandle } val chargerDetails: MediatorLiveData> by lazy { MediatorLiveData>().apply { + value = state["chargerDetails"] listOf(chargerSparse, referenceData).forEach { addSource(it) { _ -> val charger = chargerSparse.value val refData = referenceData.value if (charger != null && refData != null) { - loadChargerDetails(charger, refData) + if (charger.id != value?.data?.id) { + loadChargerDetails(charger, refData) + } } else { value = null } } } + observeForever { + // persist data in case fragment gets recreated + state["chargerDetails"] = it + } } } val charger: MediatorLiveData> by lazy { diff --git a/app/src/main/java/net/vonforst/evmap/viewmodel/Utils.kt b/app/src/main/java/net/vonforst/evmap/viewmodel/Utils.kt index 2d9fe757..7ba74692 100644 --- a/app/src/main/java/net/vonforst/evmap/viewmodel/Utils.kt +++ b/app/src/main/java/net/vonforst/evmap/viewmodel/Utils.kt @@ -1,5 +1,6 @@ package net.vonforst.evmap.viewmodel +import android.os.Parcelable import androidx.annotation.MainThread import androidx.annotation.Nullable import androidx.lifecycle.* @@ -7,6 +8,8 @@ import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Job import kotlinx.coroutines.delay import kotlinx.coroutines.launch +import kotlinx.parcelize.Parcelize +import kotlinx.parcelize.RawValue import java.util.concurrent.atomic.AtomicBoolean @@ -24,9 +27,13 @@ enum class Status { /** * A generic class that holds a value with its loading status. - * @param - */ -data class Resource(val status: Status, val data: T?, val message: String?) { + * + * Note that this class implements Parcelable for convenience, but will give a runtime error when + * trying to write it to a Parcel if the type parameter does not implement Parcelable. + */ +@Parcelize +data class Resource(val status: Status, val data: @RawValue T?, val message: String?) : + Parcelable { companion object { fun success(data: T?): Resource { return Resource(Status.SUCCESS, data, null)