I wonder how I should be properly using the @ReadO...
# compose
s
I wonder how I should be properly using the @ReadOnlyComposable annotation in this example: Got a function which I want to use in order to receive an instance of a java.time.format.DateTimeFormatter. My first implementation was this:
Copy code
@Composable
fun customDateTimeFormatter(): DateTimeFormatter {
  val locale = getLocale()
  return remember(locale) {
    DateTimeFormatterBuilder().stuff().toFormatter(locale)
  }
}
But I wonder is this the right place do do just this instead (without the remember)
Copy code
@Composable
@ReadOnlyComposable
fun customDateTimeFormatter(): DateTimeFormatter {
  val locale = getLocale()
  return DateTimeFormatterBuilder.stuff().toFormatter(locale)
  }
}
Would this give me the same guarantees that • I only need to evaluate this once and it gets remembered properly, so I don’t call the formatter builder on each recomposition • If Locale changes for some reason, it will in fact recompose and give me the updated value
For reference,
getLocale()
is also a
@ReadOnlyComposable
. It’s this
Copy code
@Composable
@ReadOnlyComposable
fun getLocale(): Locale {
  val configuration = LocalConfiguration.current
  return ConfigurationCompat.getLocales(configuration).get(0) ?: LocaleListCompat.getAdjustedDefault()[0]!!
}
a
I only need to evaluate this once and it gets remembered properly, so I don’t call the formatter builder on each recomposition
I don't know where the expectation comes from, but I don't think Compose will automatically remember the return value for you and
@ReadOnlyComposable
doesn't change this.
s
Hmm I think what I was looking for is for this evaluation to be skipped as long as the the composable is called once, and then there are no inputs and
getLocale()
return value does not change either. But you are right, it’s a wrong assumption to make. I think composable functions that return values aren’t skipped in the same way that other composable functions are right? I’ve tried to find some source to read about how value returning composables are different but haven’t been able to yet. What I am really looking for is just the
rememberX
style of functions. So something like this:
Copy code
@Composable
fun rememberCustomDateTimeFormatter(): DateTimeFormatter {
  val locale = getLocale()
  return remember(locale) { DateTimeFormatterBuilder().stuff().toFormatter(locale) }
}
At least that’s what I think I want here 😄