Skip to content

Instantly share code, notes, and snippets.

@uteke

uteke/Model.kt Secret

Last active September 1, 2023 11:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save uteke/82ab1337f354db45bf7bc42a29a6ed16 to your computer and use it in GitHub Desktop.
Save uteke/82ab1337f354db45bf7bc42a29a6ed16 to your computer and use it in GitHub Desktop.
class Model<ViewState, Action, Mutation, Event>(
private val actionProcessors: Collection<ActionProcessor<Action, Mutation, Event>>,
private val reducers: Collection<Reducer<Mutation, ViewState>>,
private val coroutineScope: CoroutineScope,
private val viewMutableStateFlow: MutableStateFlow<ViewState>,
private val eventChannel: Channel<Event>,
) {
val viewStateFlow: Flow<ViewState> = viewMutableStateFlow
val eventFlow: Flow<ViewState> = eventChannel.receiveAsFlow()
fun process(action: Action) {
coroutineScope.launch {
actionProcessors
.map { actionProcessor -> actionProcessor(action) }
.merge()
.collect { value ->
mutation?.let(::handleMutation)
event?.let(eventChannel::trySend)
}
}
}
private fun handleMutation(mutation: Mutation) {
reducers
.asIterable()
.forEach { reducer ->
viewMutableStateFlow.update { currentState ->
reducer.invoke(mutation, currentState)
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment