Hi guys, I wrote simple code to passing any of typ...
# android
t
Hi guys, I wrote simple code to passing any of type for navigate between screens.
Copy code
object Transformer {
    private var transformerMap = mutableMapOf<String, Any>()

    fun put(key: String, t: Any) {
        transformerMap[key] = t
    }

    fun pull(key: String): Any {
        return transformerMap[key]!!
    }
}
The logic is simple, When you use the navigate function you have to put the parameters which you want to send Where you use the Composable function, you need to pull it and give it as a parameter. It is perfectly working. I am wondering that is this wrong way ?
z
this is some /r/programminghorror material. I love it
c
Yeah, this pattern is a nightmare for a thousand reasons, and theres no good reason to do it like this. ViewModels and NavGraph args both exist for doing this exact kind of thing, but they give you tons of benefits around type safety and strong guarantees around the existence of that data, that this Transformer class will never have. Not to mention this code breaks all of the fundamental principles of Compose: that data should be immutable and Composables should be pure functions free of side effects. Since it’s a global object, it means the
composable()
route is no longer a pure function. And since your Transformer class is not immutable (it’s using
mutableMapOf()
) there’s the possibility of new values put into the map being changed unintentionally in the receiving route. And consider that Composables may be run many times, so doing a
pull
in the route will only work for the first time it’s composed, but break if it ever gets recomposed for some reason.
So long story short: pass simple primitive values directly through NavArgs, and non primitive values like the
Movie
should not be directly passed at all. Just pass the ID of that Movie in NavArgs, and let the destination screen fetch that Movie by the ID that was passed to it.
t
I understood very well, it really helped a lot. Thank you 🙏