I am saving the size of a composable using the onSizeChanged
modifier. I want to know what the size of the composable was during the previous configuration so that when the configuration changes, I can do a calculation with that size. However, I want to wait until my calculation finishes before I start saving the size again based on the new configuration.
Right now I'm passing the size to MyComposable
. MyComposable
is the only one who cares about what the size was during the last configuration (landscape or portrait), so I thought I would save the size within its scope. I have no idea when the configuration change happens, so I keep updating a variable oldSize
whenever there is a new size to hopefully save the most recent value before the configuration changes.
Below is the code of how I manage the size within MyComposable
. It seems to work, but is there a more straightforward way of doing this?
@Composable
fun MyComposable(
size: () -> IntSize,
) {
// save size across configurations
var oldSize by rememberSaveable(stateSaver = IntSizeSaver) {
mutableStateOf(IntSize.Zero)
}
var updateSize by remember { mutableStateOf(false) }
if (updateSize) {
LaunchedEffect(size()) { oldSize = size() }
}
LaunchedEffect(true) {
// do stuff with oldSize...
myFunction(oldSize)
// allow oldSize to be updated again
updateSize = true
}
}
I am guessing if I wanted to put some of this logic into some kind of composable function, it would look something like this. I used rememberUpdatedState
as a guide.
@Composable
fun <T> rememberUpdatedStateSaveable(
newValue: T,
stateSaver: Saver<T, out Any>,
enableUpdates: Boolean
): State<T> = rememberSaveable(stateSaver = stateSaver) {
mutableStateOf(newValue)
}.apply { value = if (enableUpdates) newValue else value }
If I update the original code so that it uses my custom rememberUpdatedStateSaveable
, then it looks like this:'
@Composable
fun MyComposable(
size: () -> IntSize,
) {
var updateSize by remember { mutableStateOf(false) }
// save size across configurations
val oldSize by rememberUpdatedStateSaveable(
newValue = size(),
stateSaver = IntSizeSaver,
enableUpdates = updateSize
)
LaunchedEffect(true) {
// do stuff with oldSize...
myFunction(oldSize)
// allow oldSize to be updated again
updateSize = true
}
}