Hello, I'm trying to use a `SharedViewModel` in or...
# android
o
Hello, I'm trying to use a
SharedViewModel
in order to preserve data saved in
SavedStateHandle
through a flow of screens after process death, let me explain: I have a flow of screens: A, B & C where each screen “contributes” data to a single data holder. Then the final screen, screen C takes all that data and use it. I’ve implemented a
SharedViewModel
and inject it to all consumers screens via
hiltNavGraphViewModel
&
@AssistedInject
(
@AssistedInject
is used in order to inject the
SharedViewModel
into each screen’s
ViewModel
). Everything works fine, I’m able to get the same
SharedViewModel
instance and each screen can contribute his data where finally screen C can use it (everything works, happy flow). The issue starts with
process death
- I’ve tried to save the
SharedViewModel
data as a
Parcelable
with his own
SavedStateInstance
but as soon as I simulate process death, when the screen loads and the
SharedViewModel
is injected, I get
null
when I try to access the saved data. I’ve attached the
SharedViewModel
and the Parcelable model in the thread. Has anyone stumbled upon this behavior?
not kotlin but kotlin colored 4
Copy code
@HiltViewModel
class SharedViewModel @Inject constructor(
    private val savedStateHandle: SavedStateHandle,
) : ViewModel() {

    var data = initializeData()
        set(value) {
            savedStateHandle[SavedStateHandleDataKey] = value
            field = value
        }

    private fun initializeData(): SharedData {
        val savedData: SharedData? = savedStateHandle[SavedStateHandleDataKey] //Here it's null after process death
        return savedStateHandle[SavedStateHandleDataKey] ?: SharedData()
    }

    companion object {
        private const val SavedStateHandleDataKey = "data"
    }
}

@Parcelize
data class SharedData(
    val amount: Double = 0.0,
) : Parcelable