updateWith

context(viewModel: ViewModel)
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:

  1. Sets loading = true before starting the operation

  2. Executes the operation in the ViewModel's coroutine scope

  3. Preserves existing data on success (no data changes)

  4. Sets error event on failure

  5. Sets loading = false when 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

T

The type of the screen data.

operation

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

suspendRunCatching

for wrapping repository operations in Result

Samples

dev.atick.feature.home.ui.home.HomeViewModel.deleteJetpackdev.atick.feature.auth.ui.signin.SignInViewModel.signInWithGoogledev.atick.feature.auth.ui.signin.SignInViewModel.loginWithEmailAndPassword