I create an object with a composable function "ren...
# compose
v
I create an object with a composable function "render" with a delagated field
Copy code
var field by remember (mutableStateOf(initialState))
where initial state is passed into the class on construction. I then construct a new instance of this class and the problems begin. It recieves a new version of initialState (as it should because I passed in a different one) but then the delegation just keeps the old value. It is incredibly weird because this is a completely new object. Any ideas?
I do know remember has some sort of caching or something maybe thats it? very odd error
a
Block inside
remember
has no knowledge of changes outside it unless you explicitly tell it there are changes:
Copy code
remember(initialState) { mutableStateOf(initialState) }
Generally though, you shouldn't want this behaviour because now you have two sources of truth. One via the initial param, and one is the remembered state you're creating.
In the child composable, are you changing
field
later on? If yes, when does parent change
initialState
? Don't you think these should be merged so that changes are done only in one place? For example, you could do this:
Copy code
@Composable
Parent() {
    var value by remember { mutableStateOf(initialValue) }
    Child(value, { value = it })
}

@Composable
Child(value: Any, updateField: (Any) -> Unit) {
    // Fire off an update for whatever reason
    // Parent updates state variable which will recompose child
    updateField(newValue)
}
v
My viewmodel structure is pretty bad which is why i have to do this. The child composables are in a class. I destroy that class and make a new instance. What you are saying makes sense, and since functions are shared across all instances, Im not actually destroying the function am i? so the remember sticks and actually remembers the value. If i want to destroy it I need to not remember it...
@ascii THANKS your litttle code block made realize that what I am really doing is calling 2 functions just in a lot of boilerplate kind of way. The fix was to simply not remember the the state as it simply got destroyed anyways when I was done. 🙂
👍 1
100 Views