updateWith
inline fun <T : Any> MutableStateFlow<UiState<T>>.updateWith(crossinline operation: suspend T.() -> Result<Unit>)
Updates the UI state with the result of an async operation that performs an action without returning new data.
This function automatically handles the complete async operation lifecycle:
Sets
loading = truebefore starting the operationExecutes the operation in the ViewModel's coroutine scope
Preserves existing data on success (no data changes)
Sets error event on failure
Sets
loading = falsewhen complete
Use this function for async operations that perform actions but don't update screen data:
Saving/updating data without changing current view
Deleting items
Sending analytics events
Triggering background jobs
Any operation that returns
Result<Unit>
Kotlin Context Parameters
This function uses Kotlin's context parameters feature (context(viewModel: ViewModel)). The ViewModel context provides implicit access to viewModelScope for launching coroutines. You never need to pass the ViewModel explicitly - it's automatically available when called from within a ViewModel.
Usage Example
@HiltViewModel
class SettingsViewModel @Inject constructor(
private val repository: SettingsRepository
) : ViewModel() {
private val _uiState = MutableStateFlow(UiState(SettingsScreenData()))
val uiState = _uiState.asStateFlow()
fun saveSettings() {
_uiState.updateWith {
repository.saveSettings(this) // Returns Result<Unit>
}
}
fun deleteAccount() {
_uiState.updateWith {
repository.deleteAccount() // Returns Result<Unit>
}
}
}Parameters
The type of the screen data.
Suspend lambda that receives current data and returns Result<Unit>. Typically calls a repository method that performs an action.
See also
for synchronous updates
for async operations that return new data
for wrapping repository operations in Result