updateOptimistically

suspend fun <T> updateOptimistically(stateUpdate: (S) -> S, stateIfFailed: (S) -> S, work: suspend () -> T): T

Changes the state at once, runs work, and puts the state back if the work does not finish.

Use it to show the result of an action before the action is done, so the user does not wait:

store.updateOptimistically(
stateUpdate = { it.copy(favorite = true) },
stateIfFailed = { it.copy(favorite = false) },
) {
profiles.setFavorite(profileId, favorite = true)
}

stateUpdate and stateIfFailed only change what the screen shows; neither does any work. The repository call, or whatever the action really is, goes in work and nowhere else.

When work throws, the exception goes on to the caller after the state is put back, so a handler that uses this still reports its failure to the screen's ErrorHandler. A work that is cancelled counts as not finished: the state is put back as well.

Use this for state that only this screen holds. If something else replaces the same part of the state while work runs, such as a handler that observes a repository, it overwrites the change. For data like that, let its owner (the repository) show the change early and take it back.

Return

What work returns.

Parameters

stateUpdate

Makes the state the screen shows at once. Runs right away, like update.

stateIfFailed

Makes the state the screen goes back to. Runs only if work throws or is cancelled. It receives the state as it is at that moment, so undo only what stateUpdate did: other changes made in the meantime are then kept.

work

The action itself.