Richard Onslow Roper
Richard Onslow Roper

Reputation: 6835

Does `remember` only work with `MutableState` variables?

I was just doing some testing for one of my Composables when I found this very bizarre behaviour.

This code:-

{ //Composable-Scope
 var fired = remember { false }
 if(!fired) { Fire(); fired = true }
}

calls the methof Fire() on every recomposition.

On the other hand, however,

{ //Composable Scope
 var fired by remember { mutableStateOf(false) }
 if(!fired) { Fire(); fired = true }
}

calls Fire() only upon the first Composition.

If this is the intended behaviour, is there a good explanation for why remember is not made universal? If it is not the intended behavior, I'll probably just file a bug.

Upvotes: 2

Views: 614

Answers (2)

Swetabh Suman
Swetabh Suman

Reputation: 159

// use this

yes, this will work only with mutablestate, but you can use mutablestate without remember to define global variable = like ----------

var showSheet by remember { mutableStateOf(false) }

var showSheet by mutableStateOf(false)

    if (showSheet) {
        BottomSheet() {
            showSheet = false
        }
    } 

Upvotes: 0

Phil Dukhov
Phil Dukhov

Reputation: 87794

This is intended behaviour.

During the first composition value of remember lambda is calculated and cached. On each next recomposition calling remember { ... } will return the cached value.

In your first code block you're creating a variable, which will get the same initial value on each recomposition. You can modify it during the composition code, but on recomposition it'll be reset, as if you were not using remember at all.

With mutable state remember does the same thing: it remembers the content of the lambda. But in this case the result is a wrapper class instance. This instance is the same between recompositions, but you can modify the value property of this object, that's why it lives thought recompositions.

Upvotes: 3

Related Questions