HelloCW
HelloCW

Reputation: 2285

Why can't I get the same instance of class when I have used remember in Android Jetpack Compose?

After I run the code A, I find s1.hashCode() and s2.hashCode() return different values after UI recomposition.

I have added remember keyword for the function rememberOtherState(), why can't I get the same instance of class when I have used remember in Android Jetpack Compose ?

class OtherState (context: Context) {
    ...
}

@Composable
fun rememberOtherState(): OtherState {
    val context = LocalContext.current
    return remember {
        OtherState(context)
    }
}


@Composable
fun TitleWithToolBar(   
) {
    val s1=rememberOtherState()
    val s2=rememberOtherState()
    
    Row(
        modifier = Modifier            
    ) {

        log(s1.hashCode().toString()+" S1")
        log(s2.hashCode().toString()+" S2")

    ...
}

Upvotes: 2

Views: 60

Answers (1)

chuckj
chuckj

Reputation: 29585

remember is positional. Every call to rememberOtherState will return a different instance of OtherState but will return the same instance every time TitleWithToolBar is recomposed.

For more details on positional memoization and consider reading: https://newsletter.jorgecastillo.dev/p/positional-memoization-in-jetpack

Upvotes: 3

Related Questions