haroldadmin / Vector

Kotlin Coroutines based MVI architecture library for Android
https://haroldadmin.github.io/Vector/
Apache License 2.0
193 stars 9 forks source link

Add support for restoring state from SavedStateHandle in Vector state factory #17

Open haroldadmin opened 4 years ago

haroldadmin commented 4 years ago

Is your feature request related to a problem? Please describe. VectorStateFactory tries two approaches to create an initial state: Using the VectorViewModelFactory and using the constructor.

For applications using the SavedStateVectorViewModel, it becomes necessary to implement VectorViewModelFactory's initialState() method to restore this state from the SavedStateHandle, even though the most basic implementation here simply retrieves the state from the handle and returns it.

Describe the solution you'd like An automated restoration of state from the SavedStateHandle in the case where the ViewModel does not implement the factory interface's initialState() method.

haroldadmin commented 4 years ago

Implementation for this would be go somewhat like this:

// VectorStateFactory

override fun <S : VectorState> createInitialState(
  vmClass: KClass<*>,
  stateClass: KClass<out S>,
  handle: SavedStateHandle,
  owner: ViewModelOwner
): S {
  return getStateFromVectorVMFactory(vmClass, handle, owner)
    ?: getPersistedState(handle)
    ?: getDefaultStateFromConstructor(stateClass)
    ?: throw UnInstantiableStateClassException(stateClass.java.simpleName)
}

fun <S: VectorState> getPersistedState(handle: SavedStateHandle): S? {
  return handle[SavedStateVectorViewModel.KEY_SAVED_STATE]
}

This will work correctly only when the state has been saved using KEY_SAVED_STATE. If the user uses a different implementation of the persistState() method then the retrieved persisted state might be incomplete, or null.

Looks like this is infeasible using this solution.