HelloCW
HelloCW

Reputation: 2305

How can I remember a string which is from stringArrayResource( ) when I use Jetpack Compose?

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

}

Upvotes: 6

Views: 1334

Answers (1)

Thracian
Thracian

Reputation: 67208

@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)
}

Upvotes: 1

Related Questions