Last active
March 20, 2021 20:51
-
-
Save green-nick/3defb12c387c614879e4544c5706c1f8 to your computer and use it in GitHub Desktop.
WIP: Delegate which will automatically handle onSaveInstanceState/onRestoreInstanceState of property
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package * | |
import android.util.* | |
import androidx.core.os.bundleOf | |
import androidx.savedstate.SavedStateRegistryOwner | |
import kotlin.properties.ReadWriteProperty | |
import kotlin.reflect.KProperty | |
inline fun <reified T : Any?> SavedStateRegistryOwner.savedState(initValue: T) = | |
object : ReadWriteProperty<SavedStateRegistryOwner, T> { | |
private var value: T = initValue | |
private lateinit var key: String | |
private lateinit var mainKey: String | |
override fun setValue(thisRef: SavedStateRegistryOwner, property: KProperty<*>, value: T) { | |
tryRegister(property.name) | |
this.value = value | |
} | |
override fun getValue(thisRef: SavedStateRegistryOwner, property: KProperty<*>): T { | |
tryRegister(property.name) | |
value = savedStateRegistry.consumeRestoredStateForKey(mainKey)?.get(key) as? T ?: value | |
return value | |
} | |
private fun tryRegister(propertyName: String) { | |
if (::key.isInitialized) return | |
key = "savedState.$propertyName" | |
mainKey = this@savedState::class.java.name + "." + key | |
savedStateRegistry.registerSavedStateProvider(mainKey) { | |
bundleOf(key to value) | |
} | |
} | |
} | |
inline fun <reified T : Any?> SavedStateRegistryOwner.savedState() = savedState<T?>(null) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment