atick-faisal/Jetpack-Compose-Starter

Simplify state update process in the ViewModels

Closed this issue · 0 comments

Add helper function like following:

inline fun <T : Any> MutableStateFlow<UiState<T>>.updateState(crossinline update: T.() -> T) {
    update { UiState(update(it.data)) }
}

context(ViewModel)
inline fun <T : Any> MutableStateFlow<UiState<T>>.updateStateBy(
    crossinline operation: suspend () -> Result<T>,
) {
    if (value.loading) return
    viewModelScope.launch {
        update { it.copy(loading = true) }
        val result = operation()
        if (result.isSuccess) {
            val data = result.getOrNull()
            if (data != null) {
                update { it.copy(data = data, loading = false) }
            } else {
                update { it.copy(error = IllegalStateException("Operation returned null")) }
            }
        } else {
            update { it.copy(error = result.exceptionOrNull()) }
        }
    }
}