Skip to content

Instantly share code, notes, and snippets.

@kaszabimre
Last active July 7, 2023 14:11
Show Gist options
  • Save kaszabimre/289516951d61a8ba725ea415dda407cc to your computer and use it in GitHub Desktop.
Save kaszabimre/289516951d61a8ba725ea415dda407cc to your computer and use it in GitHub Desktop.
Reducer.kt with StateFlowAdaptable
interface StateFlowAdaptable {
val stateFlowAdapter: FlowAdapter<*>
val errorFlowAdapter: FlowAdapter<*>
}
interface UiState
interface UiEvent
abstract class Reducer<S : UiState, E : UiEvent>(initialVal: S) : ViewModel(), StateFlowAdaptable {
//...
private val _state: MutableStateFlow<S> = MutableStateFlow(initialVal)
val state: StateFlow<S>
get() = _state
private val _error: MutableStateFlow<String?> = MutableStateFlow(null)
val error: StateFlow<String?>
get() = _error
override val stateFlowAdapter = state.asCallbacks()
override val errorFlowAdapter = error.asCallbacks()
private fun <T : Any?> StateFlow<T>.asCallbacks() = FlowAdapter(viewModelScope, this)
//...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment