Created
July 6, 2022 20:04
-
-
Save VitalyPeryatin/b1be38259ddd9bb450bd436d6cf1d74d to your computer and use it in GitHub Desktop.
This file contains 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
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