Composable Function

rememberUpdatedState

[remember] a [mutableStateOf] [newValue] and update its value to [newValue] on each recomposition of the [rememberUpdatedState] call.

rememberUpdatedStateSampleWithDisposableEffect

@Suppress("UnnecessaryLambdaCreation")
fun rememberUpdatedStateSampleWithDisposableEffect() {
    @Composable
    fun EventHandler(dispatcher: Dispatcher, onEvent: () -> Unit) {
        val currentOnEvent by rememberUpdatedState(onEvent)
        // Event handlers are ordered and a new onEvent should not cause us to re-register,
        // losing our position in the dispatcher.
        DisposableEffect(dispatcher) {
            val disposable =
                dispatcher.addListener {
                    // currentOnEvent will always refer to the latest onEvent function that
                    // the EventHandler was recomposed with
                    currentOnEvent()
                }
            onDispose { disposable.dispose() }
        }
    }
}

rememberUpdatedStateSampleWithLaunchedEffect

fun rememberUpdatedStateSampleWithLaunchedEffect() {
    @Composable
    fun NotificationHost(state: NotificationState, onTimeout: (Notification) -> Unit) {
        val currentOnTimeout by rememberUpdatedState(onTimeout)
        state.currentNotification?.let { currentNotification ->
            LaunchedEffect(currentNotification) {
                // We should not restart this delay if onTimeout changes, but we want to call
                // the onTimeout we were last recomposed with when it completes.
                delay(NotificationTimeout)
                currentOnTimeout(currentNotification)
            }
        }
        // ...
    }
}