Is doing (date, price, phone number) formatting ba...
# compose
u
Is doing (date, price, phone number) formatting bad for compose? should it be pushed to viewmodel? Trouble it if I preformat everything (phone number, date & time), then everything becomes String and bye bye typesafety
p
I would push it to the ViewModel. Composable code runs very often anytime a recomposition is triggered, which will execute your date formatting code unnecessarily.
s
This ^^ isn't necessarily a good reason to do this, you can always limit the recomposition to as much as it needs to be with a correct usage of a remember. If your ViewModel doesn't have the string to show itself but it comes from resources, which only the composable has access to, then it's perfectly fine to do the formatting in the composable. You can store the formatter with a
remember
and also store the result of the formatting with a remember with a key on whatever may change the input.
👍 1
p
remember
the result with a
key
is a better solution than the ViewModel. In regards to limiting recomposition, it is something we all battle and try to minimize but is hard to accomplish sometimes 😞
z
I love to have a formatter type of class for things like this, provided as a composition local globally or for a specific portion of the app. It handles caching of values, and you can just continue writing fluent UI without having to worry about remembering values. I know composition locals are sometimes discouraged to use, but I think this makes for a good case 🙂
👍 1
a
Use inline value classes to keep type safety
u
formatter is cached statically, I mean only about the formatting itself
z
By formatter I mean
interface Formatter { fun formatDate(x): String }
u
means you actually format inside the composable?
z
Yes exactly. If the date/timestamp is passed into your composable (e.g. from the viewmodel) then you pass that into the formatter and have it turned into a beautiful string. Of course, you can also choose to do all of this in a remember block in your composable, thats up to you; Im just making a case for a global formatter since that has worked well for me.
u
global formatter is a given, I was mostly arguing about where to do formatting
💪🏽 1