Stylianos Gakis
12/22/2021, 8:01 AMMonetaryAmount
from org.javamoney:moneta
in compose @Preview functions.
It seems like the JDKCurrencyProvider
isn’t yet created for the previews, therefore it fails fetching the currency. Anyone had the same issue before that can provide some workaround?
It would also be nice to be able to run a debugger on my code for the preview in order to see what fails exactly potentially? This is probably too hard though, considering I do not understand under which special rules the previews run exactly.Carl Benson
12/22/2021, 8:49 AMStylianos Gakis
12/22/2021, 8:53 AMfun MonetaryAmount.format(locale: java.util.Locale, minimumDecimals: Int = 0): String {
return NumberFormat.getCurrencyInstance(locale).also {
it.currency = Currency.getInstance(currency.currencyCode)
it.minimumFractionDigits = minimumDecimals
}.format(this.number.numberValueExact(BigDecimal::class.java))
}
Money.of(
someInt,
CurrencyUnitBuilder.of("SEK", "default").build()
)
Which works fine for the previews as it just prints out the currency code itself no matter what it is without doing any lookups, perfect for dummy data anyway.Carl Benson
12/22/2021, 9:08 AMStylianos Gakis
12/22/2021, 9:25 AMtad
12/22/2021, 9:23 PMCurrencyAmount
works fine, btwStylianos Gakis
12/23/2021, 8:54 AMtad
12/24/2021, 1:44 AMStylianos Gakis
12/24/2021, 8:50 AMtad
12/26/2021, 7:49 PMMonetaryContext
in its "immutable and thread-safe" MonetaryAmount
type, which introduces a dependency on JDKCurrencyProvider
, which needs the rest of the Moneta runtime initialized. In my opinion, having worked on Android banking apps for 10 years now, this is not a good recipe for limited-runtime use cases such as testing and UI previews, and client software in most cases can get away with a plain Currency
+ BigDecimal
data type.
I'm not saying to get rid of it, but I am suggesting to limit use of Moneta to your data layer and use a regular Kotlin data class in your UI layer, because your UI should not have to care about a working MonetaContext
and it definitely should not be doing calculations anyway.MonetaryAmount
, because that data type carries around all of the parameters needed to format and apply mathematical operations. This definitely causes issues on Android because that data is provided by the OEM, isn't updated regularly, is often incomplete, and you definitely aren't testing in all locales in which your app will be used. And most of this is useless because your backend won't (or shouldn't) trust any client-side calculations, and you end up using NumberFormat
anyway for formatting amounts.Stylianos Gakis
12/26/2021, 10:32 PMI’m just trying to help solve your problemI’ll just note that my original problem was not being able to use Compose previews with it but I mentioned higher up how I found a simple solution that fits my needs. But with that said, thanks for your advice, I do appreciate it!