Hi ! Maybe a dumb question, but does `mutableState...
# compose
l
Hi ! Maybe a dumb question, but does
mutableStateOf()
has an immutable version ? Or would that have no sense ? Because I want to have a state, but that would never change : just in order to avoid to create it each time
s
State<T>
/
MutableState<T>
you can think of this as
List<T>
/
MutableList<T>
👍 2
If you have a thing that never changes, you should just use
T
l
Thank you very much : so my question has a sense indeed 🙂
s
val neverChanges = someThing
or if it's expensive
val neverChanges = remember { someThing }
👍 1
🙏 1
Or if it changes based on some inputs:
val neverChanges = remember(o1, o2) { o1.someThing(o2) }
l
Not my use case : it is just an utility class (object can't have parameters), hence the need to keep it.
s
Ah
l
val neverChanges = remember { someThing }
: this one could save me 🙂
s
Then yea, remember is good. Just think about if you're introducing hidden state (a thing that can change, such as a var property) as a member of the class.
👍 1
l
I'll just loose delegation, but that won't be a great issue.
s
For the thread readers, you can also use delegation on properties:
Copy code
class MyClass(initialValue: SomeType) {
    var someState by mutableStateOf(initialValue)
        private set
}
(initialValue obv. optional but worth showing)
👍 1
c
State<T>
doesn’t imply that the value won’t change, it just implies that it can’t be mutated externally. Whatever logic implements the
State<T>
interface can change its own internal value and kickstart recomposition, but you get the guarantee of knowing exactly where its being changed from (such as with
Flow.collectAsState()
). If it truly never changes, it should just be a normal value not wrapped in
State<T>
👍 1
l
Thank you @Casey Brooks: I'm using this pattern
Copy code
val enginesUtils = rememberSaveable {
        ChessEngineUtils(
            appId = myAppId,
            context = currentContext
        )
    }
Where
ChessEngineUtils
is the utility class.
s
The reference to
myAppId
and
currentContext
are suspicious in a remember block without parameters. If they change should
ChessEngineUtils
be re-instantiated?
If so, use
Copy code
rememberSavable(myAppId, currentContext) { ... }
l
No, don't worry : appId is hard coded. I just had to compute local context in a val, because I must get it from a composable
👍 1