7

I hope to remember a string which is from stringArrayResource in Code A , but I get the the Error A. How can I fix it?

And more, I find more variables can't be wrapped with remember, such as val context = LocalContext.current , why?

Error A

Composable calls are not allowed inside the calculation parameter of inline fun remember(calculation: () -> TypeVariable(T)): TypeVariable(T)

Code A

@Composable
fun DialogForDBWarningValue(
    preferenceState:PreferenceState
) {
    val context = LocalContext.current   //I can't wrap with  remember

    val itemName =remember{ stringArrayResource(R.array.dBWarning_Name) }  //I can't wrap with  remember

}

2 Answers 2

1
@Composable
inline fun <T> remember(calculation: @DisallowComposableCalls () -> T): T =
    currentComposer.cache(false, calculation)

The reason for that error is @DisallowComposableCalls annotation

This will prevent composable calls from happening inside of the function that it applies to. This is usually applied to lambda parameters of inline composable functions that ought to be inlined but cannot safely have composable calls in them.

I don't know if accessing resources and getting strings would have any impact on performance but as an alternative this can be done using nullable properties, i don't think it's good practice to have nullable objects while you don't have to, by only getting resources once your String is null or an object that holds Strings and sets them on Composition or configuration changes if you wish to change new ones.

class StringHolder() {
    var str: String = ""
}

val stringHolder = remember(LocalConfiguration.current) {
    StringHolder()
}.apply {
    this.str = getString(R.string.dBWarning_Name)
}
Sign up to request clarification or add additional context in comments.

1 Comment

Boy, that's some ugly code. Too bad kotlin/compose doesn't have elegance and readability as essential features!
0

First of all, stringResource(), stringArrayResource(), etc. already use some internal caching, so you don't have to wrap them in remember { } just to improve performance.

That said, if you really have to, you can do something like this:

val resources = LocalResources.current

val string = remember(resources) { resources.getString(R.string.some_string) }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.