Skip to content

Instantly share code, notes, and snippets.

@matheusbristot
Created July 22, 2022 12:22
Show Gist options
  • Save matheusbristot/9c1733297f33c907659e3ab5b610120c to your computer and use it in GitHub Desktop.
Save matheusbristot/9c1733297f33c907659e3ab5b610120c to your computer and use it in GitHub Desktop.
Compose Navigation Support - Gson
import android.os.Bundle
import android.os.Parcelable
import androidx.navigation.NavArgumentBuilder
import androidx.navigation.NavBackStackEntry
import androidx.navigation.NavType
import androidx.navigation.navArgument
import com.google.gson.Gson
inline fun <reified T : Parcelable?> createNavArgument(
argNamed: String,
isNullableAllowed: Boolean = false
) = navArgument(argNamed) {
type = createNavType<T>(isNullableAllowed)
nullable = isNullableAllowed
}
inline fun <reified T : Parcelable?> NavArgumentBuilder.createNavType(
isNullableAllowed: Boolean = false
) = object : NavType<T>(isNullableAllowed = isNullableAllowed) {
override fun get(bundle: Bundle, key: String): T? {
return bundle.getParcelable(key)
}
override fun parseValue(value: String): T {
return Gson().fromJson(value, T::class.java)
}
override fun put(bundle: Bundle, key: String, value: T) {
bundle.putParcelable(key, value)
}
}
inline fun <reified T : Parcelable> NavBackStackEntry.getNavArgs(
argNamed: String
): T? = arguments?.getParcelable(argNamed)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment