https://kotlinlang.org logo
#compose
Title
# compose
o

Osman Saral

12/07/2023, 1:36 PM
Hi, is this a bad practice: I've implemented MutableStateFlow delegates like this
Copy code
inline operator fun <T> StateFlow<T>.getValue(thisObj: Any?, property: KProperty<*>): T = value

inline operator fun <T> MutableStateFlow<T>.setValue(thisObj: Any?, property: KProperty<*>, value: T) {
    this.value = value
}
And I use the variable like this:
var state by MutableStateFlow("foo")
On compose side:
val state = viewModel.state
I know I cannot call
collectAsStateWithLifecycle
here. But what difference does it make here?
f

Filip Wiesner

12/07/2023, 1:40 PM
The difference is that you are just reading the current state on recomposition. You are not subscribing to the changes emitted by the flow
1
o

Osman Saral

12/07/2023, 1:41 PM
this means that any change on the viewModel.state won't trigger recomposition?
Maybe using something like this will fix it?
val state by remember { mutableStateOf(viewModel.state) }
🚫 1
f

Filip Wiesner

12/07/2023, 1:44 PM
No, that won't fix it. If your state is a Flow, you have to collect it to be able to see (react to) new changes.
remember { mutableStateOf(viewModel.state) }
will actually be even worse because you'll get just the first value on every composition.
o

Osman Saral

12/07/2023, 1:45 PM
yeah you're right. okay got it. thanks for answering my silly question 🙃
f

Filip Wiesner

12/07/2023, 2:35 PM
No problem ☺️ Concepts of state and recomposition are hard from the beginning but once it clicks, it should be fine
4 Views