Skip to content

Instantly share code, notes, and snippets.

@VitalyPeryatin
Created July 6, 2022 20:04
Show Gist options
  • Save VitalyPeryatin/b1be38259ddd9bb450bd436d6cf1d74d to your computer and use it in GitHub Desktop.
Save VitalyPeryatin/b1be38259ddd9bb450bd436d6cf1d74d to your computer and use it in GitHub Desktop.
abstract class Destination(
...
) {
private var parcelableArguments: HashMap<String, Parcelable> = hashMapOf()
protected fun saveParcelableArgument(key: String, argument: Parcelable) {
parcelableArguments[key] = argument
}
@Suppress("UNCHECKED_CAST")
protected fun <T> NavBackStackEntry.extract(key: String): T? {
val argument = extendedArguments.firstOrNull { it.name == key }?.argument
return (when (argument?.type) {
NavType.IntType -> {
arguments?.getInt(key) ?: argument.defaultValue
}
NavType.FloatType -> {
arguments?.getFloat(key) ?: argument.defaultValue
}
NavType.LongType -> {
arguments?.getLong(key) ?: argument.defaultValue
}
NavType.BoolType -> {
arguments?.getBoolean(key) ?: argument.defaultValue
}
NavType.StringType -> {
arguments?.getString(key) ?: argument.defaultValue
}
else -> {
parcelableArguments[key]
}
}) as? T
}
@Suppress("UNCHECKED_CAST")
@Composable
fun <T: DestinationArguments> rememberArguments(navBackStackEntry: NavBackStackEntry): T {
parcelableArguments = rememberSaveable {
parcelableArguments
}
return remember {
getArguments(navBackStackEntry) ?: EmptyArguments
} as T
}
protected open fun getArguments(navBackStackEntry: NavBackStackEntry): DestinationArguments? {
return null
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment