rememberOptimistic
Creates and remembers an optimistic state object where the state and optimistic value are of the same type.
This is a convenience overload for when the optimistic value directly replaces the current state.
Usage:
var counter by remember { mutableStateOf(0) }
// Using destructuring declaration for cleaner access
val (optimisticState, addOptimistic) = rememberOptimistic(counter)
// Inside a coroutine scope - addOptimistic must be called within a coroutine context
scope.launch {
// Apply an optimistic update
val completion = addOptimistic(counter + 1)
// Perform the actual operation (e.g. network request)
try {
api.incrementCounter()
counter += 1
// Signal successful completion
completion(null)
} catch (e: Exception) {
// Signal error - resets optimistic state by default
completion(e)
}
}
Return
An OptimisticObject that manages optimistic updates.
Parameters
The type of both the state and optimistic values.
The initial state.
The policy that determines how to handle errors in optimistic updates.
Creates and remembers an optimistic state object that can track optimistic updates.
Optimistic updates allow showing immediate UI feedback for operations that may take time to complete, such as network requests. The UI can be updated optimistically assuming the operation will succeed, then reconciled later if it fails.
Usage:
// A list that we want to update optimistically
var items by remember { mutableStateOf(listOf("A", "B", "C")) }
// Create optimistic state with a custom update function
val (optimisticItems, addItem) = rememberOptimistic<List<String>, String>(
state = items,
updateFn = { currentList, newItem -> currentList + newItem }
)
// Inside a coroutine scope - addItem must be called within a coroutine context
scope.launch {
// Apply an optimistic update - adds the new item right away
val completion = addItem("D")
// Perform the actual operation
try {
api.addItem("D")
items = items + "D"
completion(null) // Success
} catch (e: Exception) {
completion(e) // Error - reverts the optimistic update
}
}
Return
An OptimisticObject that manages optimistic updates.
Parameters
The type of the state.
The type of the optimistic value.
The initial state.
The policy that determines how to handle errors in optimistic updates.
Function that determines how an optimistic value updates the current state.