Skip to content

Instantly share code, notes, and snippets.

@VitalyPeryatin
Created July 6, 2022 19:26
Show Gist options
  • Save VitalyPeryatin/e31385e59f4670a3977d009f0d712c7f to your computer and use it in GitHub Desktop.
Save VitalyPeryatin/e31385e59f4670a3977d009f0d712c7f to your computer and use it in GitHub Desktop.
Pass parcelable arguments (Compose)
...
override fun registerGraph(
navGraphBuilder: NavGraphBuilder,
navController: NavHostController,
modifier: Modifier,
parameters: NavGraphParameters
) {
...
navGraphBuilder.composable(VideoAnswerDestination) { navBackStackEntry ->
val arguments: VideoAnswerDestination.Arguments =
VideoAnswerDestination.rememberArguments(navBackStackEntry)
VideoAnswerScreen(
modifier = modifier,
navController = navController,
videoAnswerData = arguments.videoAnswerData
)
}
}
...
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
}
}
...
private fun navigateToVideoAnswer(
navController: NavController
) {
navController.navigate(VideoAnswerDestination.createRoute(effect.data))
}
...
import androidx.navigation.NavBackStackEntry
import com.afterglow.core_base.navigation.Destination
import com.afterglow.core_base.navigation.DestinationArguments
import **.VideoAnswerData
private const val VideoAnswerData = "VideoAnswerData"
object VideoAnswerDestination: Destination("video_answer") {
data class Arguments(
val videoAnswerData: VideoAnswerData?
): DestinationArguments
override fun getArguments(navBackStackEntry: NavBackStackEntry): Arguments {
return Arguments(
videoAnswerData = navBackStackEntry.extract(VideoAnswerData)
)
}
fun createRoute(data: VideoAnswerData): String {
saveParcelableArgument(VideoAnswerData, data)
return "video_answer"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment